forked from jakaspeh/concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconditionVariable.cpp
More file actions
72 lines (51 loc) · 1.29 KB
/
conditionVariable.cpp
File metadata and controls
72 lines (51 loc) · 1.29 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
63
64
65
66
67
68
69
70
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
enum class Laundry {CLEAN, DIRTY};
std::mutex MUT;
Laundry SONS_LAUNDRY = Laundry::CLEAN;
std::condition_variable CV;
bool is_laundry_clean()
{
return SONS_LAUNDRY == Laundry::CLEAN;
}
bool is_laundry_dirty()
{
return SONS_LAUNDRY == Laundry::DIRTY;
}
void clean_laundry()
{
std::unique_lock< std::mutex > lock(MUT);
CV.wait(lock, is_laundry_dirty);
std::cout << "Doing the son's laundry." << std::endl;
SONS_LAUNDRY = Laundry::CLEAN;
std::cout << "The laundry is clean." << std::endl;
lock.unlock();
CV.notify_one();
}
void play_around()
{
std::cout << "Playing basketball and sweating." << std::endl;
{
std::lock_guard< std::mutex > lock(MUT);
SONS_LAUNDRY = Laundry::DIRTY;
}
std::cout << "Asking mother to do the laundry." << std::endl;
CV.notify_one();
// waiting
{
std::unique_lock< std::mutex > lock(MUT);
CV.wait(lock, is_laundry_clean);
}
std::cout << "Yea, I have a clean laundry! Thank you mum!" << std::endl;
}
int main()
{
std::thread mother(clean_laundry);
std::thread son(play_around);
mother.join();
son.join();
return 0;
}