本文参考:https://kheresy.wordpress.com/2014/01/09/c11-condition-variable/
主要说明的问题是 std::condition_variable::wait 的运作过程,证明了wait在某个线程中的运作原理是使得该线程处于挂起状态,知道有“介绍等待”信号唤醒它继续执行,这个在侧面反映了操作系统信号机制。
示例代码如下所示:
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
using namespace std;
mutex gMutex;
condition_variable gCV;
void funcThread()
{
cout << "[" << this_thread::get_id() << "] Thread started." << endl;
unique_lock<mutex> mLock(gMutex);
cout << "[" << this_thread::get_id() << "] wait for wake up..." << endl;
gCV.wait( mLock );
cout << "[" << this_thread::get_id() << "] be waked up." << endl;
cout << "[" << this_thread::get_id() << "] Thread end." << endl;
}
int main( int argc, char** argv )
{
cout << "[Main] create new thread" << endl;
thread t1(funcThread);
cout << "[Main] wait 1 second" << endl;
this_thread::sleep_for( chrono::seconds(1) );
cout << "[Main] send notify" << endl;
gCV.notify_all();
cout << "[Main] wait thread stop" << endl;
t1.join();
}