-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathexer06a-blocking-queue.cpp
More file actions
103 lines (69 loc) · 1.76 KB
/
Copy pathexer06a-blocking-queue.cpp
File metadata and controls
103 lines (69 loc) · 1.76 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
/*
BLOCKING QUEUE IMPLEMENTATION
Version A: Synchronous queues
*/
#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
using namespace std;
template <typename T>
class SynchronousQueue {
private:
sem_t semPut;
sem_t semTake;
T element;
public:
SynchronousQueue<T>() {
sem_init(&semPut, 0, 1);
sem_init(&semTake, 0, 0);
}
~SynchronousQueue<T>() {
sem_destroy(&semPut);
sem_destroy(&semTake);
}
void put(const T& value) {
sem_wait(&semPut);
element = value;
sem_post(&semTake);
}
T take() {
sem_wait(&semTake);
T result = element;
sem_post(&semPut);
return result;
}
};
void* producer(void* arg) {
auto syncQueue = (SynchronousQueue<std::string>*) arg;
auto arr = { "lorem", "ipsum", "foo" };
for (auto&& data : arr) {
cout << "Producer: " << data << endl;
syncQueue->put(data);
cout << "Producer: " << data << "\t\t\t[done]" << endl;
}
pthread_exit(nullptr);
return nullptr;
}
void* consumer(void* arg) {
auto syncQueue = (SynchronousQueue<std::string>*) arg;
std::string data;
sleep(5);
for (int i = 0; i < 3; ++i) {
data = syncQueue->take();
cout << "\tConsumer: " << data << endl;
}
pthread_exit(nullptr);
return nullptr;
}
int main() {
SynchronousQueue<std::string> syncQueue;
pthread_t tidProducer, tidConsumer;
int ret = 0;
ret = pthread_create(&tidProducer, nullptr, &producer, &syncQueue);
ret = pthread_create(&tidConsumer, nullptr, &consumer, &syncQueue);
ret = pthread_join(tidProducer, nullptr);
ret = pthread_join(tidConsumer, nullptr);
return 0;
}