std::condition_variable用于线程同步,配合std::mutex实现等待-通知机制,如生产者-消费者模型中,通过wait()阻塞线程直到条件满足,notify_one()或notify_all()唤醒线程,需用unique_lock并结合谓词防止虚假唤醒,确保正确处理共享状态。

在C++多线程编程中,std::condition_variable 是实现线程间同步的重要工具之一。它通常与 std::mutex 配合使用,用于让一个或多个线程等待某个条件成立,而另一个线程在条件满足时通知等待的线程继续执行。
基本概念:条件变量的作用
条件变量不是用来保护共享数据的,而是用来协调线程之间的执行顺序。比如生产者-消费者模型中,消费者线程需要等待缓冲区非空,而生产者在放入数据后可以通知消费者。这时就适合使用 std::condition_variable。
关键组件包括:
- std::condition_variable:提供 wait、notify_one、notify_all 接口
- std::unique_lock<:mutex>:必须配合 unique_lock 使用,不能用 lock_guard
- 共享条件判断:通常是一个布尔表达式,表示某种状态是否成立
基本用法示例:生产者-消费者模型
下面是一个简单的例子,演示如何使用条件变量实现两个线程间的协作:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
std::queue<int> data_queue;
std::mutex mtx;
std::condition_variable cv;
bool finished = false;
void producer() {
for (int i = 0; i < 5; ++i) {
std::lock_guard<std::mutex> lock(mtx);
data_queue.push(i);
std::cout << "生产: " << i << "\n";
lock.unlock(); // 提前释放锁
cv.notify_one(); // 通知一个消费者
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
{
std::lock_guard<std::mutex> lock(mtx);
finished = true;
}
cv.notify_all(); // 通知所有等待线程结束
}
void consumer() {
while (true) {
std::unique_lock<std::mutex> lock(mtx);
// 条件等待:队列为空且未结束,则等待
cv.wait(lock, [] {
return !data_queue.empty() || finished;
});
if (!data_queue.empty()) {
int value = data_queue.front();
data_queue.pop();
std::cout << "消费: " << value << "\n";
}
if (data_queue.empty() && finished) {
break; // 结束循环
}
lock.unlock();
}
}
主函数启动线程:
int main() {
std::thread p(producer);
std::thread c(consumer);
p.join();
c.join();
return 0;
}
wait 的正确使用方式
cv.wait() 必须传入一个 unique_lock,并可选地传入一个谓词(lambda 或函数对象)。推荐始终使用带谓词的版本,避免虚假唤醒导致的问题。
两种写法对比:
- 不推荐:
cv.wait(lock);
if (!data_queue.empty()) { ... } - 推荐:
cv.wait(lock, []{ return !data_queue.empty(); });
带谓词的 wait 会自动循环检查条件,直到为真才返回,更安全简洁。
notify_one vs notify_all
- notify_one:唤醒一个等待的线程,适用于只有一个线程需要被通知的情况(如单个消费者)
- notify_all:唤醒所有等待线程,适用于广播场景,例如多个消费者都在等任务
注意:notify 不保证立即切换到目标线程,只是使其进入就绪状态。
基本上就这些。掌握 condition_variable 的核心在于理解“等待某个条件 + 锁保护共享状态 + 正确通知”的模式。实际使用中要特别注意锁的粒度和 notify 的时机,避免死锁或遗漏唤醒。










