-
Notifications
You must be signed in to change notification settings - Fork 0
/
Assigment4ConditionVariables.cpp
53 lines (48 loc) · 1.3 KB
/
Assigment4ConditionVariables.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
51
52
53
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <string>
using namespace std;
using namespace std::chrono;
// Global variables
mutex mut;
condition_variable cv;
string sdata{ "Empty" };
bool data_ready{ false };
// Waiting thread
void reader() {
while(true)
{
unique_lock<std::mutex> lg(mut); // Acquire lock
while(!data_ready)
{
lg.unlock();
std::this_thread::sleep_for(10ms);
lg.lock();
}
if (data_ready) break;
}
cout << "Data is " << sdata << endl;
}
// Modyifing thread
void writer() {
cout << "Writing data..." << endl;
lock_guard<std::mutex> lg(mut); // Acquire lock
std::this_thread::sleep_for(2s); // Pretend to be busy...
sdata = "Populated"; // Modify the data
data_ready = true; // Notify the flag
}
int main() {
cout << "Data is " << sdata << endl;
thread read{ reader };
thread write{ writer };
/*
// If the writer thread finishes before the reader thread starts, the notification is lost
thread write{writer};
std::this_thread::sleep_for(500ms);
thread read{reader};
*/
write.join();
read.join();
}