-
Notifications
You must be signed in to change notification settings - Fork 1
/
SimpleProducerConsumer.cpp
63 lines (50 loc) · 1.18 KB
/
SimpleProducerConsumer.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
// https://levelup.gitconnected.com/producer-consumer-problem-using-mutex-in-c-764865c47483
#include <iostream>
#include <mutex>
#include <cstdlib>
#include <chrono>
#include <thread>
std::mutex g_mutex;
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()
{
while (true) {
while (!g_ready) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::unique_lock<std::mutex> ul(g_mutex);
consumeData(g_data);
g_ready = false;
}
}
void producerFunc()
{
while (true) {
std::unique_lock<std::mutex> ul(g_mutex);
g_data = producerData();
g_ready = true;
ul.unlock();
while (g_ready) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
}
int main()
{
std::thread consumerThread(consumerFunc);
std::thread producerThread(producerFunc);
consumerThread.join();
producerThread.join();
return 0;
}