-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrency4-producerConsumer.cpp
84 lines (68 loc) · 2.09 KB
/
concurrency4-producerConsumer.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
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
class Semaphore {
private:
std::mutex mutex_;
std::condition_variable condition_;
unsigned long count_ = 0; // Initialized as locked.
public:
Semaphore(int value){
count_ = value;
}
void release() {
std::lock_guard<std::mutex> lock(mutex_);
++count_;
condition_.notify_one();
}
void acquire() {
std::unique_lock<std::mutex> lock(mutex_);
while(!count_) // Handle spurious wake-ups.
condition_.wait(lock);
--count_;
}
};
std::mutex mtx;
std::queue<int> buffer;
const unsigned int MAX_BUFFER_SIZE = 10;
Semaphore empty_slots(MAX_BUFFER_SIZE); // Semaphore for empty slots
Semaphore filled_slots(0); // Semaphore for filled slots
void producer(int value) {
empty_slots.acquire(); // Wait if there are no empty slots
{
std::lock_guard<std::mutex> lock(mtx); // slightly more effective than unique_lock, auto acquire, release on constructor and destructor
buffer.push(value);
std::cout << "Producing " << value << std::endl;
std::cout << "Buffer size after producing: " << buffer.size() << std::endl << std::endl;
}
filled_slots.release(); // Signal that a slot has been filled
}
void consumer() {
filled_slots.acquire(); // Wait if there are no filled slots
int value;
{
std::lock_guard<std::mutex> lock(mtx);
value = buffer.front();
buffer.pop();
std::cout << "Consuming " << value << std::endl;
std::cout << "Buffer size after consuming: " << buffer.size() << std::endl << std::endl;
}
empty_slots.release(); // Signal that a slot has been emptied
}
int main() {
std::thread producerThread([] {
for (int i = 1; i <= 20000; ++i) {
producer(i);
}
});
std::thread consumerThread([] {
for (int i = 1; i <= 20000; ++i) {
consumer();
}
});
producerThread.join();
consumerThread.join();
return 0;
}