分享C++11代码片段-mutex

mutex即是互斥的意思。

直接看代码吧:

#include 
#include 
#include 

using namespace std;

void RunUnsynchronized() {
  long sharedCounter = 0;

  /* simply increment in each thread the shared counter */
  auto increment = [&sharedCounter](){
    for(int i = 0; i < 1000; ++i)
      ++sharedCounter;
  };

  thread firstThread(increment);
  thread secondThread(increment);

  firstThread.join();
  secondThread.join();

  cout << "unsynchronized shared counter: " << sharedCounter << " (expected to be 2000)" << endl;
}

void RunSynchronized() {
  long sharedCounter = 0;
  mutex sharedMutex;

  /* locks the mutex and increments; guard is destroyed by leaving scope */
  auto increment = [&sharedCounter, &sharedMutex](){
    lock_guard scopedMutex(sharedMutex);

    for(int i = 0; i < 1000; ++i)
      ++sharedCounter;
  };

  thread first_thread(increment);
  thread second_thread(increment);

  first_thread.join();
  second_thread.join();

  cout << "synchronized shared counter: " << sharedCounter << " (expected to be 2000)" << endl;
}

int main() {
  RunUnsynchronized();
  RunSynchronized();
}

上面的代码挺简单的,这里就不做过多的解释了。只是有一个问题:

为什么使用了std::lock_guard 而不是 mutex.lock() 和 mutex.unlock()?

先看一下cppreference上怎么说的:
http://en.cppreference.com/w/cpp/thread/mutex

std::mutex is usually not accessed directly: std::unique_lock and std::lock_guard are used to manage locking in an exception-safe manner.

说白了,就是使用guard可以通过RAII确保异常安全,避免内存泄漏。

如果您不懂RAII,看这里:
《c++中的RAII》
http://blog.csdn.net/wangshubo1989/article/details/52133213

unique_lock和lock_guard有什么区别?

lock_guard使用起来比较简单,除了构造函数外没有其他member function,在整个区域都有效。

unique_guard除了lock_guard的功能外,提供了更多的member_function,相对来说更灵活一些。

你可能感兴趣的:(c++11,C++)