使用unique_lock而非lock_guard是因为wait需自动释放并重获锁,而lock_guard不支持中途解锁。

用 std::mutex 配合 std::queue 和 std::condition_variable 就能写出一个真正可用的线程安全队列,核心是保护共享状态、避免忙等待、支持阻塞式读写。
基础模板:带锁+条件变量的阻塞队列
以下是一个泛型、线程安全、支持 push/pop 阻塞等待的队列实现:
#include <queue>
#include <mutex>
#include <condition_variable>
template <typename T>
class ThreadSafeQueue {
private:
std::queue<T> queue_;
mutable std::mutex mutex_;
std::condition_variable cond_not_empty_;
std::condition_variable cond_not_full_; // 可选:若加容量限制才需要
public:
void push(T value) {
std::lock_guard<std::mutex> lock(mutex_);
queue_.push(std::move(value));
cond_not_empty_.notify_one(); // 通知可能在 wait 的 pop
}
bool try_pop(T& result) {
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty()) return false;
result = std::move(queue_.front());
queue_.pop();
return true;
}
void wait_and_pop(T& result) {
std::unique_lock<std::mutex> lock(mutex_);
cond_not_empty_.wait(lock, [this] { return !queue_.empty(); });
result = std::move(queue_.front());
queue_.pop();
}
};
登录后复制
为什么用 unique_lock 而不是 lock_guard 做 wait?
cond_not_empty_.wait() 必须传入 std::unique_lock,因为 wait 会自动释放锁、挂起线程,等被唤醒后再重新加锁。lock_guard 不支持中途解锁,无法配合 condition_variable 使用。
- wait 内部先 unlock,避免其他线程无法 push
- 唤醒后自动 re-lock,保证临界区安全
- 使用谓词(lambda)可防止虚假唤醒
要不要加容量限制?
如果希望队列有上限(比如避免内存爆掉),可以扩展:
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
还木有评论哦,快来抢沙发吧~