c++併發編程之互斥鎖(mutex)的使用方法

轉載:c++併發編程之互斥鎖(mutex)的使用方法

 

方法1:直接操作 mutex,即直接調用 mutex 的 lock / unlock 函數

#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>

boost::mutex mutex;
int count = 0;

void Counter() {
  mutex.lock();

  int i = ++count;
  std::cout << "count == " << i << std::endl;

  // 前面代碼如有異常,unlock 就調不到了。
  mutex.unlock();
}

int main() {
  // 創建一組線程。
  boost::thread_group threads;
  for (int i = 0; i < 4; ++i) {
    threads.create_thread(&Counter);
  }

  // 等待所有線程結束。
  threads.join_all();
  return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章