C++线程锁的简单例子

本文参考: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();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值