-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_binary_semaphore.cpp
More file actions
43 lines (33 loc) · 1.02 KB
/
02_binary_semaphore.cpp
File metadata and controls
43 lines (33 loc) · 1.02 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
#include <iostream>
#include <thread>
#include <semaphore>
using namespace std;
std::binary_semaphore smpSignalMainToThread{0}, smpSignalThreadToMain{0};
// g++ --std=c++20 02_binary_semaphore.cpp && ./a.out
void ThreadFunc()
{
/**
* IMP: Wait for a signal from the main thread by attempting to decrement the semaphore
*/
smpSignalMainToThread.acquire();
cout << "[Thread]: Got the signal\n";
this_thread::sleep_for(3s);
cout << "[Thread]: Send the signal\n";
// Notify the main thread
smpSignalThreadToMain.release();
}
int main()
{
thread worker(ThreadFunc);
cout << "[Main]: Send the signal\n";
/** IMP: signal the worker to start working by incrementing the semaphore count
* Release => Increment
* Acquire => Decrement
*/
smpSignalMainToThread.release();
// wait till the worker is done doing the work by attempting to decrement
smpSignalThreadToMain.acquire();
if (worker.joinable())
worker.join();
cout << "[Main] Got the signal";
}