-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcondition_variable.cpp
More file actions
53 lines (43 loc) · 1.31 KB
/
condition_variable.cpp
File metadata and controls
53 lines (43 loc) · 1.31 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
// http://www.cplusplus.com/reference/condition_variable/condition_variable/
// GB add sleep + prints
// condition_variable example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
std::mutex mtxCout;
void print_id (int id) {
{ std::unique_lock<std::mutex> lock(mtx); // GB
std::cout << "thread " << id << " waiting\n";
} // GB
std::unique_lock<std::mutex> lck(mtx);
while (!ready) cv.wait(lck);
// ...
// { std::unique_lock<std::mutex> lock(mtx);
std::cout << "thread " << id << '\n';
// }
}
void go() {
std::cout << "GO!\n";
std::unique_lock<std::mutex> lck(mtx);
ready = true;
// GB either notify_all, or notify_one:
// cv.notify_all();
for (int i=0; i<10; ++i)
cv.notify_one();
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_id,i);
std::this_thread::sleep_for (std::chrono::milliseconds(1000));
std::cout << "\nafter sleeping for 1000 msec, the 10 threads should be ready to race...\n\n";
go(); // go!
for (auto& th : threads) th.join();
return 0;
}