-
Notifications
You must be signed in to change notification settings - Fork 0
/
cv.cpp
50 lines (43 loc) · 1.26 KB
/
cv.cpp
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
// condition_variable::wait (with predicate)
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::yield
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
int cargo = 0;
bool shipment_available() {return cargo!=0;}
void consume (int n) {
for (int i=0; i<n; ++i) {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck,shipment_available);
// consume:
std::cout << cargo << '\n';
cargo=0;
}
}
void produce (int n) {
for (int i=0; i<10; ++i) {
while (shipment_available()) std::this_thread::yield();
std::unique_lock<std::mutex> lck(mtx);
cargo = i+1;
std::cout << i << ": sent " << cargo << std::endl;
cv.notify_one();
}
}
int main ()
{
std::thread producer_thread (produce, 10);
std::thread consumer_thread (consume,10);
// produce 10 items when needed:
// for (int i=0; i<10; ++i) {
// while (shipment_available()) std::this_thread::yield();
// std::unique_lock<std::mutex> lck(mtx);
// cargo = i+1;
// std::cout << i << ": sent " << cargo << std::endl;
// cv.notify_one();
// }
producer_thread.join();
consumer_thread.join();
return 0;
}