-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblocking_queue.cpp
More file actions
69 lines (62 loc) · 1.78 KB
/
blocking_queue.cpp
File metadata and controls
69 lines (62 loc) · 1.78 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
#include <queue>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <chrono>
#include <thread>
#include <iostream>
template<typename T>
class BlockingQueue{
public:
explicit BlockingQueue(int cap):capacity_(cap){}
void push(T item){
std::unique_lock<std::mutex> lock(mtx_);
not_full_.wait(lock, [&](){return q_.size() < capacity_;});
q_.push(std::move(item));
not_empty_.notify_one();
}
T pop(){
std::unique_lock<std::mutex> lock(mtx_);
not_empty_.wait(lock, [&](){return !q_.empty();});
T item = std::move(q_.front());
q_.pop();
not_full_.notify_one();
return item;
}
size_t size(){
std::unique_lock<std::mutex> lock(mtx_);
return q_.size();
}
private:
std::mutex mtx_;
size_t capacity_;
std::condition_variable not_full_; // 这里用了两个条件变量,语义更清晰,当然用一个也可以。
std::condition_variable not_empty_;
std::queue<T> q_; // 底层队列容器
};
int main(){
BlockingQueue<int> bq(2);
std::thread t1([&](){
bq.push(999);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));// 1s
});
std::thread t2([&](){
bq.push(777);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));// 1s
});
std::thread t3([&](){
bq.push(666);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));// 1s
});
std::this_thread::sleep_for(std::chrono::milliseconds(5000));// 1s
auto a = bq.pop();
std::cout << a << bq.size() << std::endl;
a = bq.pop();
std::cout << a << bq.size() << std::endl;
a = bq.pop();
std::cout << a << bq.size() << std::endl;
t1.join();
t2.join();
t3.join();
return 0;
}