C++条件变量

概述

条件变量的使用,其实是一种多线程通知模式,当线程一使用完数据后,通过条件变量通知其他线程,C++11后开始支持。

说明

条件变量必须配合mutex使用,确保并发访问的排他性

std::unique_lock<std::mutex> lock(m);

线程让自我挂起,释放锁, 等待条件匹配

若next == index为false则线程挂起,释放锁,直到被唤醒;唤醒后再判断next == index,若为false则继续挂起,直到被唤醒同时条件为true。

   

 cv.wait(lock, [=]{return next == index; });
    ...

发送通知以唤醒等待队列中所有线程
   

cv.notify_all();

主线程等待线程结束

     

t.join

其他条件变量函数
notify_one                    通知一个等待的线程
notify_all                      通知所有等待的线程
wait                              阻塞当前线程,直到条件变量被唤醒
wait_for                        阻塞当前线程,直到条件变量被唤醒,或到指定时限时长后
wait_until                      阻塞当前线程,直到条件变量被唤醒,或直到抵达指定时间点
native_handle               返回原生句柄

     

测试代码

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

std::mutex m;
std::condition_variable cv;
std::vector<int> result;
int next = 0;

void worker(int index) {
  for (int i = 0; i < 10; i++) {
    std::unique_lock<std::mutex> lock(m);
    cv.wait(lock, [=]{return next == index; });
    std::cout << "worker " << index << "\n";
    result.push_back(index);
    next = next + 1;
    if (next > 2) { next = 1; };
    cv.notify_all();
  }
}

int main() {
  std::thread worker1(worker, 1);
  std::thread worker2(worker, 2);
  {
    std::lock_guard<std::mutex> l(m);
    next = 1;
  }
  std::cout << "Start\n";
  cv.notify_all();
  worker1.join();
  worker2.join();
  for (int e : result) {
    std::cout << e << ' ';
  }
  std::cout << std::endl;
}

运行结果


我公司承接各类技术服务,主要聚焦于:stm32、单片机、嵌入式、QT应用开发、Web+Python+Django应用开发。欢迎合作。

  • 24
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汉森教育

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值