-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsumer_producer_condivar.cpp
More file actions
103 lines (94 loc) · 2.62 KB
/
consumer_producer_condivar.cpp
File metadata and controls
103 lines (94 loc) · 2.62 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
#include <cstdio>
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
#include <thread>
#include <mutex>
#include <future>
#include <chrono>
#include <future>
using namespace std;
class ConsumerProducer {
public:
ConsumerProducer() = default;
void consumer ();
void producer ();
void getresults(void);
void test() {
f = p.get_future();
std::thread getRes( [this] () {getresults();} );
std::thread cons( [this] () {consumer ();} );
std::thread prod( [this] () {producer ();} );
cons.join();
prod.join();
getRes.join();
std::cout << "test: leaving " << std::endl;
}
private:
std::mutex amutex;
std::condition_variable cv;
static constexpr int empty = 0;
static constexpr int full = 10;
int tank = full;
int enough{};
std::promise<int> p;
std::future<int> f;
bool done{false};
};
// nov 29th comments
int main ()
{
ConsumerProducer a;
a.test();
return 0;
}
void ConsumerProducer::getresults (void) {
f.wait();
std::cout << "getResults: get() " << f.get() << std::endl;
std::cout << "getResutls: closing bar: Done... " << std::endl;
cv.notify_all();
}
void ConsumerProducer::consumer () {
std::unique_lock <std::mutex> mylock(amutex, std::defer_lock);
std::cout << "consumer: entering... " << std::endl;
while (true) {
mylock.lock();
while (tank == empty) {
std::cout << "consumer: tank is empty, waiting: tank: " << tank << std::endl;
cv.wait (mylock);
}
tank--;
std::cout << "consumer: what's left: tank: " << tank << std::endl;
std::this_thread::sleep_for (std::chrono::seconds(1));
mylock.unlock();
enough++;
if(enough == 50) {
done = true;
std::cout << "consumer: leaving: drank enough Done... " << std::endl;
p.set_value(50); // how much did the consumer consume?
break;
}
cv.notify_all();
}
}
void ConsumerProducer::producer () {
std::unique_lock <std::mutex> mylock(amutex, std::defer_lock);
std::cout << "producer: entering... " << std::endl;
while (true) {
mylock.lock();
while (tank != empty) {
std::cout << "producer: tank is NOT empty, waiting: tank: " << tank << std::endl;
cv.wait (mylock);
if(done){
std::cout << "producer: bar closed: Done... " << std::endl;
return;
}
}
tank = full;
std::cout << "producer: a full tank: tank: " << tank << std::endl;
std::this_thread::sleep_for (std::chrono::seconds(1));
mylock.unlock();
cv.notify_all();
}
}