condition_variable条件变量

Posted 顾文繁

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;


以上是关于condition_variable条件变量的主要内容,如果未能解决你的问题,请参考以下文章

condition_variable条件变量

condition_variable条件变量

[多线程]C++11多线程-条件变量(std::condition_variable)

详解 C++ 多线程的condition_variable

C++ std::condition_variable 是什么 有什么用 条件变量 线程同步

[C++多线程]1.3-多线程控制的另一种姿势-条件变量(condition_variable), 信号量(semaphore)