-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathexer06b01-blocking-queue.cpp
More file actions
134 lines (88 loc) · 2.44 KB
/
Copy pathexer06b01-blocking-queue.cpp
File metadata and controls
134 lines (88 loc) · 2.44 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
/*
BLOCKING QUEUE IMPLEMENTATION
Version B01: General blocking queues
Underlying mechanism: Semaphores
*/
#include <iostream>
#include <queue>
#include <string>
#include <stdexcept>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
using namespace std;
template <typename T>
class BlockingQueue {
private:
int capacity = 0;
sem_t semRemain;
sem_t semFill;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
std::queue<T> q;
public:
BlockingQueue(int capacity) {
if (capacity <= 0)
throw std::invalid_argument("capacity must be a positive integer");
this->capacity = capacity;
sem_init(&semRemain, 0, capacity);
sem_init(&semFill, 0, 0);
}
~BlockingQueue() {
sem_destroy(&semRemain);
sem_destroy(&semFill);
pthread_mutex_destroy(&mut);
}
void put(const T& value) {
int ret = 0;
ret = sem_wait(&semRemain);
ret = pthread_mutex_lock(&mut);
q.push(value);
ret = pthread_mutex_unlock(&mut);
ret = sem_post(&semFill);
}
T take() {
T result;
int ret = 0;
ret = sem_wait(&semFill);
ret = pthread_mutex_lock(&mut);
result = q.front();
q.pop();
ret = pthread_mutex_unlock(&mut);
ret = sem_post(&semRemain);
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;
}