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