-
Notifications
You must be signed in to change notification settings - Fork 0
/
codeforces.cpp
52 lines (40 loc) · 889 Bytes
/
codeforces.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
#include <bits/stdc++.h>
using namespace std;
std::mutex m;
std::condition_variable cv;
deque<int> buffer;
int max_capacity = 1000;
void producer(int val)
{
while(val)
{
std::unique_lock<std::mutex> lock(m);
cv.wait(lock , []() {return buffer.size() <= max_capacity;});
buffer.push_back(val);
cout<<"Produced : "<<val<<endl;
val--;
lock.unlock();
cv.notify_one();
}
}
void consumer()
{
while(true)
{
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, []() {return buffer.size() > 0;});
int val = buffer.back();
buffer.pop_back();
cout<<"Consumed : "<<val<<endl;
lock.unlock();
cv.notify_one();
}
}
int main()
{
std::thread t1(producer, 100);
std::thread t2(consumer);
t1.join();
t2.join();
return 0;
}