-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathExample.cpp
More file actions
130 lines (100 loc) · 3.12 KB
/
Copy pathExample.cpp
File metadata and controls
130 lines (100 loc) · 3.12 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <iostream>
#include <thread>
#include <atomic>
#include <mutex>
#include <queue>
#include "Event.h"
class Log
{
public:
template <typename T>
static void printLine(T arg)
{
std::lock_guard<std::recursive_mutex> lock(getMutexInstance());
std::cout << arg << std::endl;
}
template <typename T, typename ...Args>
static void printLine(T arg, Args... args)
{
std::lock_guard<std::recursive_mutex> lock(getMutexInstance());
std::cout << arg;
printLine(args...);
}
private:
static std::recursive_mutex &getMutexInstance()
{
static std::recursive_mutex mutex;
return mutex;
}
};
class ProducerConsumer
{
public:
ProducerConsumer() :
notification(false, false),
terminated(false)
{
threads.push_back(std::thread(&ProducerConsumer::producerThread, this));
const unsigned numberOfConsumers = 4;
for (unsigned consumerId = 0; consumerId < numberOfConsumers; consumerId++)
threads.push_back(std::thread(&ProducerConsumer::consumerThread, this, consumerId));
}
~ProducerConsumer()
{
terminated = true;
notification.change(true);
notification.set();
for(auto &thread : threads)
if (thread.joinable())
thread.join();
}
private:
Moya::Event notification;
std::mutex productsLock;
std::queue<int> products;
std::atomic<bool> terminated;
std::vector<std::thread> threads;
void producerThread()
{
for (int productId = 1; !terminated; productId++) {
Log::printLine("[ProducerConsumer] Producing ", productId);
produce(productId);
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
}
void consumerThread(int consumerId)
{
while (!terminated) {
notification.wait();
if (terminated)
break;
int productId;
while (consume(productId)) {
Log::printLine("[ProducerConsumer] Consumer ", consumerId, " consumes ", productId);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
}
void produce(int &productId)
{
std::lock_guard<std::mutex> lock(productsLock);
products.push(productId);
notification.set();
}
bool consume(int &productId)
{
std::lock_guard<std::mutex> lock(productsLock);
if (products.empty())
return false;
productId = products.front();
products.pop();
return true;
}
};
int main()
{
ProducerConsumer producerConsumer;
std::this_thread::sleep_for(std::chrono::seconds(4));
Log::printLine("[Main] Beginning termination procedure...");
return 0;
}