-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBlockingQueue.cc
More file actions
95 lines (79 loc) · 2.2 KB
/
Copy pathBlockingQueue.cc
File metadata and controls
95 lines (79 loc) · 2.2 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
// 在 linux 平台上,通过 `g++ BlockingQueue.cc -std=c++17 -lpthread` 编译即可
#include <queue>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <thread>
#include <iostream>
#include <algorithm>
template<typename T>
class BlockingQueue
{
public:
BlockingQueue(size_t cap): capacity_(cap) {}
void push(const T& data) {
std::unique_lock<std::mutex> lock(mu_);
while (queue_.size() >= capacity_) {
std::cout << "queue is full, blocking" << std::endl;
fullCond_.wait(lock);
}
queue_.push(data);
emptyCond_.notify_one();
}
size_t size() const {
std::unique_lock<std::mutex> lock(mu_);
return queue_.size();
}
T pop() {
std::unique_lock<std::mutex> lock(mu_);
while (queue_.empty()) {
std::cout << "queue is empty, blocking" << std::endl;
emptyCond_.wait(lock);
}
auto value = queue_.front();
queue_.pop();
fullCond_.notify_one();
return value;
}
private:
std::queue<T> queue_;
size_t capacity_;
std::mutex mu_;
std::condition_variable emptyCond_;
std::condition_variable fullCond_;
};
int main() {
std::mutex printMu;
BlockingQueue<int> q(2);
auto push = [&q, &mu=printMu](std::vector<int> data){
for (auto num: data) {
{
std::lock_guard<std::mutex> lock(mu);
std::cout << std::this_thread::get_id() << ": push " << num << std::endl;
}
q.push(num);
}
};
auto pop = [&q, &mu=printMu](size_t count) {
{
std::lock_guard<std::mutex> lock(mu);
std::cout << std::this_thread::get_id() << ": wait for 1s, then start pop" << std::endl;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
while (count--) {
auto num = q.pop();
{
std::lock_guard<std::mutex> lock(mu);
std::cout << std::this_thread::get_id() << ": pop = " << num << std::endl;
}
}
};
std::thread t1(std::bind(push, std::vector<int>({1,2,3,4})));
std::thread t2(std::bind(pop, 8));
std::this_thread::sleep_for(std::chrono::seconds(2));
std::thread t3(std::bind(push, std::vector<int>({5,6,7,8})));
t1.join();
t2.join();
t3.join();
return 0;
}