-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathdemo22a-blocking-queue.cpp
More file actions
67 lines (45 loc) · 1.27 KB
/
Copy pathdemo22a-blocking-queue.cpp
File metadata and controls
67 lines (45 loc) · 1.27 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
/*
BLOCKING QUEUES
Version A: A slow producer and a fast consumer
Blocking queues in C++ POSIX threading are not supported by default.
So, I use mylib::BlockingQueue for this demonstration.
*/
#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include "mylib-blockingqueue.hpp"
using namespace std;
using namespace mylib;
void* producer(void* arg) {
auto blkQueue = (BlockingQueue<string>*) arg;
sleep(2);
blkQueue->put("Alice");
sleep(2);
blkQueue->put("likes");
sleep(2);
blkQueue->put("singing");
pthread_exit(nullptr);
return nullptr;
}
void* consumer(void* arg) {
auto blkQueue = (BlockingQueue<string>*) arg;
string data;
for (int i = 0; i < 3; ++i) {
cout << "\nWaiting for data..." << endl;
data = blkQueue->take();
cout << " " << data << endl;
}
pthread_exit(nullptr);
return nullptr;
}
int main() {
pthread_t tidProducer, tidConsumer;
auto blkQueue = BlockingQueue<string>();
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;
}