mutex.lock与unique_lock

时间:2016-06-21 13:29:43

标签: c++ concurrency locking mutex

我应该何时更喜欢第一段代码到第二段,并且它们有根本差异

std::mutex mtx;
mtx.lock();
... //protected stuff
mtx.unlock();
... //non-protected stuff
mtx.lock();
... //etc

std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
... //protected stuff
lck.unlock();
... //non-protected stuff
lck.lock();
... //etc

我确实知道lock_guard基本上是一个没有锁定和解锁功能的unique_lock,但是我很难用互斥锁来区分互斥锁和锁。

2 个答案:

答案 0 :(得分:28)

是的,std::unique_lock调用解析器中的互斥锁解锁。

这样做的好处是,如果抛出一些异常,您确定在离开定义std::unique_lock的范围时互斥锁将解锁。

答案 1 :(得分:8)

这样想:

// define a mutex
std::mutex mtx;

......很久以后......

void something_safe()
{

  // code in these braces is a critical section
  {
    auto lock = std::unique_lock<std::mutex>(mtx); // equivalent to mtx.lock();
    ... //protected stuff
  }  // <---- however you leave this brace, equivalent to mtx.unlock();

  ... //non-protected stuff
}