条件变量与同步模式
condition_variable 等待通知、生产者消费者、虚假唤醒、notify_all
条件变量与同步模式
condition_variable 让线程在条件满足前休眠——不空转 CPU。生产者消费者是其经典应用。
学完本章你将: 掌握 condition_variable 等待通知、虚假唤醒、notify_all。
生产者消费者
cpp
#include <queue>
#include <mutex>
#include <condition_variable>
std::queue<int> q;
std::mutex mtx;
std::condition_variable cv;
bool done = false;
void producer() {
for (int i = 0; i < 5; i++) {
std::this_thread::sleep_for(100ms);
{
std::lock_guard lk(mtx);
q.push(i);
}
cv.notify_one(); // 唤醒一个消费者
}
{
std::lock_guard lk(mtx);
done = true;
}
cv.notify_all(); // 通知所有——生产结束
}
void consumer(int id) {
while (true) {
std::unique_lock lk(mtx);
cv.wait(lk, [] { return !q.empty() || done; }); // 等条件
if (!q.empty()) {
int item = q.front(); q.pop();
lk.unlock(); // 处理数据时释放锁
std::cout << "消费者" << id << ": " << item << "\n";
} else if (done) {
break;
}
}
}
wait 的正确写法
cpp
// ❌ 错误——可能错过通知(先检查条件后 wait 之间丢失 notify)
if (condition_not_met)
cv.wait(lk);
// ✅ 正确——循环检查 + 谓词
cv.wait(lk, [] { return condition; });
// 等价于: while (!condition) { cv.wait(lk); }
// 虚假唤醒:OS 可能无故唤醒线程——所以必须用 while 循环检查