在C ++ 11线程中通过同步原语断开循环

时间:2015-03-03 12:15:44

标签: multithreading mutex

是否有人知道如何以比以下示例更传统和有效的方式打破循环/线程?

#include <mutex>
#include <thread>

std::mutex m;
int cnt = 0;

void foo() {
  while(!m.try_lock()){
    ++cnt;
  }
}

int main() {
  m.lock();
  std::thread th(&foo);
  // Some other code...  
  m.unlock(); // Unlock m to break the loop.
  // Some other code...  
}

给定示例的优点和缺点? THX!

0 个答案:

没有答案