condition_variable条件变量

有次面试,面试官问我有没有了解过条件变量(之前看的Linux高性能服务器编程书中,绝对提到了这个,都忘光了),我回答没有。。。。
今天回过头来,整理一下。

这里是引用Condition variable
A condition variable is an object able to block the calling thread until notified to resume.It uses a unique_lock (over a mutex) to lock the thread when one of its wait functions is called. The thread remains blocked until woken up by another thread that calls a notification function on the same condition_variable object.Objects of type condition_variable always use unique_lock to wait: for an alternative that works with any kind of lockable type, see condition_variable_any

这是cplusplus对条件编程的定义。condition_variable使用时需要结合unique_lock一块使用,因为guard_lock仅仅依靠了RAII,并没有对锁的粒度进一步操控。condition_variable有两个基本操作wait和notify,这两个操作有几个相应的构造函数,对应是何条件(判断条件,事件条件)。举一个例子

#include <condition_variable>
#include <string>
#include <iostream>
#include <mutex>

std::mutex mtx;
std::condition_variable cv;
volatile static int cargo = 0;

bool shipment_available()
{
    return cargo != 0;
}

void productor()
{
    for(int i = 0;i < 100;i++)
    {
        while(shipment_available())
            this_thread::yield();
        std::unique_lock<std::mutex> ul(mtx);
        cargo = i+1;
        cv.notify_one();
    }
}
void consumer(int n)
{
    for(int i = 0;i < n;i++)
    {
        std::unique_lock<std::mutex> ul(mtx);
        cv.wait(ul, shipment_available);
        cout << cargo << "\n";
        cargo = 0;
    }
}

int main(int argc, char *argv[])
{

    thread pro(productor);
    thread con(consumer, 100);

    pro.join();
    con.join();
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

顾文繁

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

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

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

打赏作者

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

抵扣说明:

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

余额充值