-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathblocking_queue.h
More file actions
72 lines (55 loc) · 1.27 KB
/
Copy pathblocking_queue.h
File metadata and controls
72 lines (55 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
68
69
70
71
72
#ifndef BLOCKING_QUEUE_INCLUDED
#define BLOCKING_QUEUE_INCLUDED
/**
* A simple blocking queue.
*
* Use push() to add items, pop() to remove items, and front()
* to get the item at the front of the queue.
*
* See blocking_queue_demo.cpp for example.
*
*/
#include <queue>
#include <mutex>
#include <condition_variable>
template<typename E>
class blocking_queue
{
private:
std::mutex _mtx;
std::condition_variable _cond;
int _max_size;
std::queue<E> _queue;
public:
blocking_queue(int max_size): _max_size(max_size)
{
}
void push(E e)
{
std::unique_lock<std::mutex> lock(_mtx);
_cond.wait(lock, [this](){ return _queue.size() < _max_size; });
_queue.push(e);
lock.unlock();
_cond.notify_one();
}
E front()
{
std::unique_lock<std::mutex> lock(_mtx);
_cond.wait(lock, [this](){ return !_queue.empty(); });
return _queue.front();
}
void pop()
{
std::unique_lock<std::mutex> lock(_mtx);
_cond.wait(lock, [this](){ return !_queue.empty(); });
_queue.pop();
lock.unlock();
_cond.notify_one();
}
int size()
{
std::lock_guard<std::mutex> lock(_mtx);
return _queue.size();
}
};
#endif