-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy path200 A Blocking Queue.cpp
More file actions
89 lines (69 loc) · 1.5 KB
/
Copy path200 A Blocking Queue.cpp
File metadata and controls
89 lines (69 loc) · 1.5 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
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
using namespace std;
template<typename E>
class blocking_queue
{
private:
mutex _mtx;
condition_variable _cond;
int _max_size;
queue<E> _queue;
public:
blocking_queue(int max_size): _max_size(max_size)
{
}
void push(E e)
{
unique_lock<mutex> lock(_mtx);
_cond.wait(lock, [this](){ return _queue.size() < _max_size; });
_queue.push(e);
lock.unlock();
_cond.notify_one();
}
E front()
{
unique_lock<mutex> lock(_mtx);
_cond.wait(lock, [this](){ return !_queue.empty(); });
return _queue.front();
}
void pop()
{
unique_lock<mutex> lock(_mtx);
_cond.wait(lock, [this](){ return !_queue.empty(); });
_queue.pop();
lock.unlock();
_cond.notify_one();
}
int size()
{
lock_guard<mutex> lock(_mtx);
return _queue.size();
}
};
int main()
{
blocking_queue<int> qu(3);
thread t1([&](){
for(int i = 0; i < 10; i++)
{
cout << "pushing " << i << endl;
cout << "queue size is " << qu.size() << endl;
qu.push(i);
}
});
thread t2([&](){
for(int i = 0; i < 10; i++)
{
auto item = qu.front();
qu.pop();
cout << "consumed " << item << endl;
}
});
t1.join();
t2.join();
return 0;
}