C++ <condition_variable>
系统讲解 C++11 条件变量 <condition_variable> 的挂起等待与通知唤醒机制、非模板类定位、带谓词 wait 防虚假唤醒以及带干净退出信号的生产者-消费者模型。
学完这一章,你能够
- 系统讲解 C++11 条件变量 <condition_variable> 的挂起等待与通知唤醒机制、非模板类定位、带谓词 wait 防虚假唤醒以及带干净退出信号的生产者-消费者模型。
条件变量同步原理与核心接口
在多线程协作中,单纯靠互斥锁反复轮询某个共享状态既浪费 CPU 又延迟高。C++11 `<condition_variable>` 头文件提供了条件变量同步机制,允许线程在条件尚未成立时原子性地释放互斥锁并进入休眠等待,直到其他线程修改共享状态并发出通知后再将其唤醒。需要准确区分的是:`std::condition_variable` 本身是一个**普通非模板类**(专为 `std::unique_lock<std::mutex>` 优化;若需搭配其他任意锁类型才使用 `std::condition_variable_any`)。其核心成员函数包括无期限等待 `wait()`、限时等待 `wait_for()` 与 `wait_until()`,以及唤醒单个等待者的 `notify_one()` 和广播唤醒全部等待者的 `notify_all()`。
生产者-消费者模型与安全退出设计
经典生产者-消费者队列模型使用一个 `std::mutex` 保护共享队列 `std::queue<int>`,再配一个 `std::condition_variable` 协调生产与消费:生产者加锁入队后调用 `cv.notify_one()`;消费者在持有 `std::unique_lock<std::mutex>` 时调用 `cv.wait(lck, pred)` 等待队列非空。**重要工程修正**:若消费者写成无退出条件的 `while (true)` 死循环,当所有生产者结束后消费者将永久阻塞在 `wait()` 上导致 `join()` 死锁;完整实现必须维护受同一互斥锁保护的 `producers_done` 完成标志,令等待谓词写为 `[&]{ return !product.empty() || producers_done; }`,并在全部生产者汇合后加锁置 `producers_done = true` 并调用 `cv.notify_all()`,确保全部剩余产品被消费完毕后消费者优雅退出。
使用规范与离线多线程实测
正确使用 `std::condition_variable` 须遵循三项铁律:第一,调用 `wait` 系列方法前必须先通过 `std::unique_lock<std::mutex>` 获取关联互斥锁,修改共享条件变量状态时也必须在同一互斥锁保护下完成(唤醒返回后锁会重新处于持有状态,随 `unique_lock` 作用域结束释放);第二,`wait`、`wait_for`、`wait_until` 在挂起期间会自动原子解锁并在唤醒前重新加锁,且**强烈推荐使用带谓词重载**(如 `cv.wait(lk, pred)`)以抵御操作系统的虚假唤醒(spurious wakeup);第三,仅需唤醒一个工作线程时用 `notify_one()`,状态广播或优雅停机时必须用 `notify_all()`。本站已在离线 Docker G++ C++17 环境实测 2 生产 2 消费完整 10 件无丢失收尾、`notify_all` 广播唤醒 3 线程及 `wait_for` 超时与提前唤醒。
实测 <condition_variable> 安全停机生产者-消费者、notify_all 广播与 wait_for 超时/唤醒
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <iostream>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>
namespace lab {
struct Case {
std::string name;
std::string expected_json;
std::string actual_json;
bool passed;
};
std::string esc(const std::string& s) {
std::string out = "\"";
for (unsigned char c : s) {
switch (c) {
case '\"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
out += buf;
} else {
out += static_cast<char>(c);
}
}
}
out += "\"";
return out;
}
std::string jbool(bool v) { return v ? "true" : "false"; }
void emit(const std::vector<Case>& cases) {
std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
for (std::size_t i = 0; i < cases.size(); ++i) {
if (i) std::cout << ", ";
std::cout << "{\"name\": " << esc(cases[i].name)
<< ", \"expected\": " << cases[i].expected_json
<< ", \"actual\": " << cases[i].actual_json
<< ", \"passed\": " << jbool(cases[i].passed) << "}";
}
std::cout << "]}\n";
}
} // namespace lab
int main() {
std::vector<lab::Case> cases;
// Case 1: bounded producer-consumer with clean shutdown flag (no infinite consumer loop)
std::mutex mtx;
std::condition_variable cv;
std::queue<int> product;
std::vector<int> consumed;
bool producers_done = false;
auto producer = [&](int id) {
for (int i = 0; i < 5; ++i) {
{
std::unique_lock<std::mutex> lck(mtx);
product.push(id * 100 + i);
}
cv.notify_one();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
};
auto consumer = [&]() {
while (true) {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, [&]() { return !product.empty() || producers_done; });
if (!product.empty()) {
int item = product.front();
product.pop();
consumed.push_back(item);
} else if (producers_done) {
break;
}
}
};
std::thread p1(producer, 1), p2(producer, 2);
std::thread c1(consumer), c2(consumer);
p1.join();
p2.join();
{
std::lock_guard<std::mutex> lck(mtx);
producers_done = true;
}
cv.notify_all();
c1.join();
c2.join();
std::sort(consumed.begin(), consumed.end());
std::vector<int> exp_items = {100, 101, 102, 103, 104, 200, 201, 202, 203, 204};
bool ok1 = (consumed == exp_items) && product.empty();
cases.push_back({
"cv_producer_consumer_bounded",
lab::jbool(true),
lab::jbool(ok1),
ok1
});
// Case 2: notify_all wakes all 3 waiting threads
std::mutex bmtx;
std::condition_variable bcv;
bool go = false;
int arrived = 0;
int woken = 0;
auto worker = [&]() {
std::unique_lock<std::mutex> lk(bmtx);
++arrived;
bcv.notify_all();
bcv.wait(lk, [&]() { return go; });
++woken;
};
std::thread w1(worker), w2(worker), w3(worker);
{
std::unique_lock<std::mutex> lk(bmtx);
bcv.wait(lk, [&]() { return arrived == 3; });
go = true;
}
bcv.notify_all();
w1.join();
w2.join();
w3.join();
cases.push_back({
"cv_notify_all_broadcast",
std::to_string(3),
std::to_string(woken),
woken == 3
});
// Case 3: wait_for timeout (false) and signaled wakeup (true)
std::mutex tmtx;
std::condition_variable tcv;
bool flag = false;
bool timed_out_res = true;
{
std::unique_lock<std::mutex> lk(tmtx);
timed_out_res = tcv.wait_for(lk, std::chrono::milliseconds(10), [&]() { return flag; });
}
std::thread notifier([&]() {
std::this_thread::sleep_for(std::chrono::milliseconds(5));
{
std::lock_guard<std::mutex> lk(tmtx);
flag = true;
}
tcv.notify_one();
});
bool woken_res = false;
{
std::unique_lock<std::mutex> lk(tmtx);
woken_res = tcv.wait_for(lk, std::chrono::milliseconds(500), [&]() { return flag; });
}
notifier.join();
bool ok3 = (!timed_out_res) && woken_res;
cases.push_back({
"cv_wait_for_timeout_and_wakeup",
lab::jbool(true),
lab::jbool(ok3),
ok3
});
lab::emit(cases);
return 0;
}
- 确认 2 生产者 2 消费者准确无丢失处理全部 10 件商品并干净退出、notify_all 广播唤醒全部 3 个等待线程,以及 wait_for 超时返回 false 且通知后返回 true。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
当前源码 SHA256:680e04799f7ead8c91cabff2612b0a60f77c497b3624fbab24fc4b9b010c47a8
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
ZIP SHA256:14effa5d43b72210cf0c74cb014626c8c8bdcde552119425cae7b26a9d39a5e2
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么调用 `cv.wait(lck, pred)` 时通常建议传入谓词 `pred`,而不是只调用单参数的 `cv.wait(lck)`?
展开参考解答
操作系统条件变量允许发生虚假唤醒(spurious wakeup),即使没有其他线程调用 `notify`,等待线程也可能提前返回;带谓词的 `wait` 内部等价于 `while (!pred()) wait(lck);`,会自动复检条件是否真正满足。