C++实现线程同步

头文件引入

#include 
#include 

变量定义

bool m_syncFlag;
std::mutex m_mtx;
std::condition_variable m_flagCond;

示例代码

subTread code

subThread()
{
  std::lock_guard lk(m_mtx);
  m_syncFlag = true;
  m_flagCond.notify_one(); 
  ...
}

main thread code

main()
{
 /*initial value is false*/
 m_syncFlag = false;
 std::unique_lock lk(m_mtx);

 /*当前线程被阻塞, 当全局标志位变为 true 之后,线程被唤醒, 继续往下*/
 pPeListener->m_flagCond.wait(lk, [pPeListener] {return pPeListener->m_syncFlag == true; });
 excute(...)
}

你可能感兴趣的:(c++,同步锁)