是否有一个std :: lock_guard的变种在构造时解锁并在C ++ 11中锁定销毁?

时间:2014-05-05 08:01:42

标签: c++ c++11 mutex std

我写了好几次代码,这些代码将受益于"反向" lock_guard,就像这个简短的例子一样。

std::lock_guard<std::mutex> lg(_eventQueueMutex);
while (!_eventQueue.empty())
{
    Event e = _eventQueue.top();

    _eventQueue.pop();
    _eventQueueMutex.unlock(); // Manual unlock
    dispatchEvent(e);
    _eventQueueMutex.lock(); // Manual lock
}

有没有办法用C ++ 11中的自动lock_guard替换内部解锁/锁定?

1 个答案:

答案 0 :(得分:9)

您可以编写自己的unlock_guard:

template <class T>
class unlock_guard {
public:
  unlock_guard(T& mutex) : mutex_(mutex) {
    mutex_.unlock();
  }

  ~unlock_guard() {
    mutex_.lock();
  }

  unlock_guard(const unlock_guard&) = delete;
  unlock_guard& operator=(const unlock_guard&) = delete;

private:
  T& mutex_;
};