-
Notifications
You must be signed in to change notification settings - Fork 1
/
SimpleProducerConsumerCond.cpp
71 lines (55 loc) · 1.34 KB
/
SimpleProducerConsumerCond.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// https://levelup.gitconnected.com/producer-consumer-problem-using-condition-variable-in-c-6c4d96efcbbc
#include <iostream>
#include <mutex>
#include <cstdlib>
#include <chrono>
#include <thread>
#include <condition_variable>
std::mutex g_mutex;
std::condition_variable g_cv;
bool g_ready = false;
int g_data = 0;
int producerData()
{
int random = std::rand() % 1000;
std::cout << "[PRODUER] : produced data : " << random << "\n";
return random;
}
void consumeData(int data)
{
std::cout << "[CONSUMER] : consumed data : " << data << "\n";
}
void consumerFunc(int times)
{
while (times > 0) {
std::unique_lock<std::mutex> ul(g_mutex);
g_cv.wait(ul, []() { return g_ready; });
consumeData(g_data);
g_ready = false;
ul.unlock();
g_cv.notify_one();
times--;
}
}
void producerFunc(int times)
{
while (times > 0) {
std::unique_lock<std::mutex> ul(g_mutex);
g_data = producerData();
g_ready = true;
ul.unlock();
g_cv.notify_one();
ul.lock();
g_cv.wait(ul, []() { return g_ready == false; });
times--;
}
}
int main()
{
int times = 100;
std::thread consumerThread(consumerFunc, times);
std::thread producerThread(producerFunc, times);
consumerThread.join();
producerThread.join();
return 0;
}