-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadsafe_queue.hpp
More file actions
54 lines (47 loc) · 1.7 KB
/
threadsafe_queue.hpp
File metadata and controls
54 lines (47 loc) · 1.7 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
#include <queue>
#include <mutex>
#include <condition_variable>
template<typename T>
class ThreadSafeQueue {
private:
std::queue<T> _queue;
std::mutex _mtx; // 保护队列操作,确保线程安全
std::condition_variable _cv; // 实现等待非空队列的阻塞操作
public:
ThreadSafeQueue() = default;
// 禁止拷贝构造和赋值操作,确保线程安全语义
ThreadSafeQueue(const ThreadSafeQueue&) = delete;
ThreadSafeQueue& operator=(const ThreadSafeQueue&) = delete;
void push(T value){
std::lock_guard<std::mutex> lock(_mtx);
_queue.push(std::move(value)); // 使用移动语义提高性能,减少拷贝开销
_cv.notify_one(); // 生产者-消费者模型
}
// 非阻塞接口
bool try_pop(T& value){
std::lock_guard<std::mutex> lock(_mtx);// 所有公共方法都保证线程安全
if(_queue.empty()){
return false;
}
value = std::move(_queue.front());
_queue.pop();
return true;
}
// 阻塞接口
void wait_and_pop(T& value){
// lock_guard: 构造时自动加锁,析构时自动解锁,不支持手动控制锁的生命周期
// unique_lock: 支持手动加锁/解锁、延迟加锁、锁所有权转移,可与条件变量配合
std::unique_lock<std::mutex> lock(_mtx);
_cv.wait(lock, [this]{return !_queue.empty();}); // 生产者消费者模型
value = std::move(_queue.front());
_queue.pop();
}
bool empty(){
std::lock_guard<std::mutex> lock(_mtx);
return _queue.empty();
}
size_t size() const{
std::lock_guard<std::mutex> lock(_mtx);
return _queue.size();
}
};