-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathblocking_queue.cpp
More file actions
59 lines (49 loc) · 1.13 KB
/
Copy pathblocking_queue.cpp
File metadata and controls
59 lines (49 loc) · 1.13 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
#include <assert.h>
#include "blocking_queue.h"
BlockingQueue::BlockingQueue() {
_quit = false;
}
BlockingQueue::~BlockingQueue() {
quit();
}
void BlockingQueue::push(int data) {
{
std::lock_guard<std::mutex> lock(_mutex);
if (_quit) {
// 程序已退出
return;
}
_queue.push(data);
}
_cond_var.notify_one();
}
int BlockingQueue::pop() {
std::unique_lock<std::mutex> lock(_mutex);
// 使用while防止虚假唤醒
while (!_quit && _queue.empty()) {
_cond_var.wait(lock, [this] { return _quit || !_queue.empty(); });
}
if (_quit) {
// 程序已退出,返回-1
return -1;
}
// 队列一定非空
assert(!_queue.empty());
int data = _queue.front();
_queue.pop();
return data;
}
size_t BlockingQueue::size() {
std::lock_guard<std::mutex> lock(_mutex);
return _queue.size();
}
bool BlockingQueue::is_empty() {
std::lock_guard<std::mutex> lock(_mutex);
return _queue.empty();
}
void BlockingQueue::quit() {
if (!_quit) {
_quit = true;
_cond_var.notify_all();
}
}