condition_variable用于线程间通信,需与std::mutex配合使用,通过wait()阻塞线程、notify_one()/notify_all()唤醒线程,避免忙等待。使用时应结合谓词防止虚假唤醒,确保在循环中检查条件,并在修改共享状态后正确调用notify。典型应用于生产者-消费者模型,保证多线程下数据安全与效率。

在C++多线程编程中,condition_variable 是实现线程间通信的重要工具之一。它通常与 std::mutex 配合使用,用于在线程之间传递状态变化的通知,避免忙等待(busy-waiting),提高程序效率和响应性。
condition_variable 本身不存储状态,它依赖于一个外部的条件变量(通常是布尔值或枚举等)来判断是否满足唤醒条件。当某个线程发现条件未满足时,它可以调用 wait() 函数将自己阻塞;而另一个线程在改变共享状态后,通过调用 notify_one() 或 notify_all() 来唤醒一个或所有等待中的线程。
关键点:
下面是一个典型的使用 condition_variable 实现生产者-消费者问题的例子:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <chrono>
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::this_thread::sleep_for(std::chrono::milliseconds(500));
std::unique_lock<std::mutex> lock(mtx);
data_queue.push(i);
lock.unlock();
cv.notify_one(); // 通知消费者
std::cout << "Produced: " << i << "\n";
}
// 生产结束
std::unique_lock<std::mutex> lock(mtx);
finished = true;
lock.unlock();
cv.notify_one();
}
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();
lock.unlock();
std::cout << "Consumed: " << value << "\n";
} else if (finished) {
break; // 无数据且已结束
}
}
std::cout << "Consumer finished.\n";
}
主函数启动两个线程:
int main() {
std::thread c(consumer);
std::thread p(producer);
c.join();
p.join();
return 0;
}
输出类似:
Produced: 0使用 condition_variable 时有几个关键细节需要注意:
除了 condition_variable,C++ 还有其他线程同步机制:
对于需要等待某个条件成立的场景,condition_variable 仍然是最常用、最高效的选择。
基本上就这些。掌握好 condition_variable 的使用模式,能让你写出更稳定、高效的并发程序。重点是理解“等待-通知”机制的本质,以及如何安全地操作共享数据。
以上就是C++ condition_variable条件变量用法_C++线程间通信实战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号