-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathexer06b02-blocking-queue.cpp
More file actions
137 lines (91 loc) · 2.69 KB
/
Copy pathexer06b02-blocking-queue.cpp
File metadata and controls
137 lines (91 loc) · 2.69 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
131
132
133
134
135
136
137
/*
BLOCKING QUEUE IMPLEMENTATION
Version B02: General blocking queues
Underlying mechanism: Condition variables
*/
#include <iostream>
#include <queue>
#include <string>
#include <stdexcept>
#include <unistd.h>
#include <pthread.h>
using namespace std;
template <typename T>
class BlockingQueue {
private:
pthread_cond_t condEmpty = PTHREAD_COND_INITIALIZER;
pthread_cond_t condFull = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
int capacity = 0;
std::queue<T> q;
public:
BlockingQueue(int capacity) {
if (capacity <= 0)
throw std::invalid_argument("capacity must be a positive integer");
this->capacity = capacity;
}
~BlockingQueue() {
pthread_cond_destroy(&condEmpty);
pthread_cond_destroy(&condFull);
pthread_mutex_destroy(&mut);
}
void put(const T& value) {
int ret = 0;
ret = pthread_mutex_lock(&mut);
while ((int)q.size() >= capacity) {
// Queue is full, must wait for 'take'
ret = pthread_cond_wait(&condFull, &mut);
}
q.push(value);
ret = pthread_mutex_unlock(&mut);
ret = pthread_cond_signal(&condEmpty);
}
T take() {
T result;
int ret = 0;
ret = pthread_mutex_lock(&mut);
while (q.empty()) {
// Queue is empty, must wait for 'put'
ret = pthread_cond_wait(&condEmpty, &mut);
}
result = q.front();
q.pop();
ret = pthread_mutex_unlock(&mut);
ret = pthread_cond_signal(&condFull);
return result;
}
};
void* producer(void* arg) {
auto blkQueue = (BlockingQueue<std::string>*) arg;
auto arr = { "nice", "to", "meet", "you" };
for (auto&& data : arr) {
cout << "Producer: " << data << endl;
blkQueue->put(data);
cout << "Producer: " << data << "\t\t\t[done]" << endl;
}
pthread_exit(nullptr);
return nullptr;
}
void* consumer(void* arg) {
auto blkQueue = (BlockingQueue<std::string>*) arg;
std::string data;
sleep(5);
for (int i = 0; i < 4; ++i) {
data = blkQueue->take();
cout << "\tConsumer: " << data << endl;
if (0 == i)
sleep(5);
}
pthread_exit(nullptr);
return nullptr;
}
int main() {
BlockingQueue<std::string> blkQueue(2); // capacity = 2
pthread_t tidProducer, tidConsumer;
int ret = 0;
ret = pthread_create(&tidProducer, nullptr, &producer, &blkQueue);
ret = pthread_create(&tidConsumer, nullptr, &consumer, &blkQueue);
ret = pthread_join(tidProducer, nullptr);
ret = pthread_join(tidConsumer, nullptr);
return 0;
}