我写了好几次代码,这些代码将受益于"反向" 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替换内部解锁/锁定?
答案 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_;
};