-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_binary_semaphore.cpp
More file actions
62 lines (50 loc) · 1.52 KB
/
Copy path20_binary_semaphore.cpp
File metadata and controls
62 lines (50 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <chrono>
#include <iostream>
#include <semaphore>
#include <thread>
// to compile this code
// g++-15 -std=c++20 20_binary_semaphore.cpp
//
//
// global binary semaphore instances
// object counts are set to zero
// objects are in non-signaled state
std::binary_semaphore
smphSignalMainToThread{0},
smphSignalThreadToMain{0};
void ThreadProc()
{
// wait for a signal from the main proc
// by attempting to decrement the semaphore
smphSignalMainToThread.acquire();
// this call blocks until the semaphore's count
// is increased from the main proc
std::cout << "[thread] Got the signal\n"; // response message
using namespace std::literals;
std::this_thread::sleep_for(3s);
std::cout << "[thread] Send the signal\n"; // message
// signal the main proc back
smphSignalThreadToMain.release();
}
int main()
{
// create some worker thread
std::thread thrWorker(ThreadProc);
std::cout << "[main] Send the signal\n"; // message
// signal the worker thread to start working
// by increasing the semaphore's count
smphSignalMainToThread.release();
// wait until the worker thread is done doing the work
// by attempting to decrement the semaphore's count
smphSignalThreadToMain.acquire();
std::cout << "[main] Got the signal\n"; // response message
thrWorker.join();
}
/*
<-----Output----->
deepankerrawat@MacBookAir Multi_Threading % ./a.out
[main] Send the signal
[thread] Got the signal
[thread] Send the signal
[main] Got the signal
*/