并发支持库(4)-条件变量

条件变量允许多个线程之间的交流。它可以阻塞某个线程,直到另一个线程的提醒再继续,这是通过关联一个互斥体来实现的。

本文章的代码库:

https://gitee.com/gamestorm577/CppStd

condition_variable

condition_variable是和mutex一起使用的条件变量,其提供了用于等待的接口wait、wait_for和wait_until,用于通知的接口notify_one和notify_all。代码示例:

std::mutex mut;
std::condition_variable cond;
bool ready = false;

auto Func1 = [&]()
{
    std::unique_lock lock(mut);
    std::cout << "Func1 lock" << std::endl;
    cond.wait(lock);
    std::cout << "Func1 finish wait" << std::endl;
};

auto Func2 = [&]()
{
    {
        std::unique_lock lock(mut);
        std::cout << "Func2 lock" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    cond.notify_one();
};

std::thread t1(Func1);
std::this_thread::sleep_for(std::chrono::seconds(1));
std::thread t2(Func2);
t1.join();
t2.join();

在这段代码中,t1线程先执行并占有了互斥mut,然后t1线程调用wait,t1线程进入等待的阻塞状态并解锁mut。然后t2线程开始执行,占有互斥mut,并在解锁mut后调用接口notify_one唤醒一个等待,t1线程被唤醒,继续执行接下来的代码。最后的输出结果为:

Func1 lock
Func2 lock
Func1 finish wait

condition_variable_any

condition_variable_any是condition_variable的泛化,可以配合更多其他类型的锁完成条件变量的功能。

notify_all_at_thread_exit

在该线程完全结束时再调用notify_all。适用于需要将局部对象析构完成再调用notify_all的场景。

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值