栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

condition

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

condition

有次面试,面试官问我有没有了解过条件变量(之前看的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 
#include 
#include 
#include 

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 ul(mtx);
        cargo = i+1;
        cv.notify_one();
    }
}
void consumer(int n)
{
    for(int i = 0;i < n;i++)
    {
        std::unique_lock 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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862234.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号