c++中如何使用条件变量_std::condition_variable多线程同步实践(如何使用.变量.多线程.同步.实践...)

wufei123 发布于 2025-09-24 阅读(66)
std::condition_variable需与std::mutex和std::unique_lock配合使用,通过wait()、notify_one()、notify_all()实现线程同步,在生产者-消费者模型中确保数据安全访问与线程正确唤醒。

c++中如何使用条件变量_std::condition_variable多线程同步实践

在C++多线程编程中,std::condition_variable 是实现线程间同步的重要工具之一。它通常与 std::mutex 配合使用,用于让一个或多个线程等待某个条件成立,而另一个线程在条件满足时通知等待的线程继续执行。

基本概念与头文件

要使用条件变量,需包含头文件:

#include <condition_variable>

核心组件包括:

  • std::condition_variable:条件变量对象,用于阻塞线程或唤醒其他线程。
  • std::unique_lock<std::mutex>:必须使用 unique_lock,因为 condition_variable 的 wait 操作需要能释放和重新获取锁。
  • wait()、notify_one()、notify_all():主要成员函数。
典型使用模式:生产者-消费者模型

下面是一个简单的生产者-消费者示例,展示如何用 std::condition_variable 实现线程同步。

#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::unique_lock<std::mutex> lock(mtx);
data_queue.push(i);
lock.unlock();
cv.notify_one(); // 唤醒一个消费者
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
{
std::unique_lock<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();
lock.unlock();
std::cout << "Consumed: " << value << std::endl;
} else if (finished) {
lock.unlock();
break; // 结束循环
}
}
std::cout << "Consumer exiting." << std::endl;
}

主函数启动线程:

int main() {
std::thread p(producer);
std::thread c1(consumer);
std::thread c2(consumer);

p.join();
c1.join();
c2.join();

return 0;
} 关键点说明

wait() 的正确使用方式

HyperWrite HyperWrite

AI写作助手帮助你创作内容更自信

HyperWrite54 查看详情 HyperWrite
  • 调用 wait 时,会自动释放锁,并使线程进入阻塞状态。
  • 当被 notify 唤醒后,线程会重新获取锁,再继续执行。
  • 推荐使用带谓词的 wait 形式:
    cv.wait(lock, predicate)
    ,避免虚假唤醒导致的问题。

notify_one vs notify_all

  • notify_one:唤醒一个等待线程,适用于只有一个线程需要处理任务的场景(如单个消费者)。
  • notify_all:唤醒所有等待线程,适合广播事件或多个消费者竞争的情况。

为什么必须用 unique_lock?

因为 condition_variable 在 wait 过程中需要临时释放互斥量,并在唤醒后重新加锁,只有 unique_lock 支持这种灵活的锁定控制。

注意事项与常见陷阱
  • 确保共享数据访问始终受 mutex 保护。
  • 避免忘记调用 notify,否则等待线程可能永远阻塞。
  • 注意 finished 标志也需要在锁内修改,保证可见性。
  • 多个消费者时,检查队列是否为空必须在锁内完成。

基本上就这些。std::condition_variable 虽然强大,但需小心使用锁和通知机制,确保逻辑正确、无死锁、无竞态条件。

以上就是c++++中如何使用条件变量_std::condition_variable多线程同步实践的详细内容,更多请关注知识资源分享宝库其它相关文章!

相关标签: 工具 ai c++ ios 数据访问 为什么 red if for while 成员函数 include break bool int void 循环 线程 多线程 Thread 对象 事件 大家都在看: C++中this指针在类成员函数中是如何工作的 C++内存泄漏检测工具使用技巧 C++工厂模式与抽象工厂区别解析 C++开发环境配置调试工具使用技巧 使用vcpkg为C++项目管理依赖库的具体步骤是什么

标签:  如何使用 变量 多线程 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。