Is there a variant of std::lock_guard that unlocks at construction and locks at destruction in C++11?

StackOverflow https://stackoverflow.com/questions/23467635

  •  15-07-2023
  •  | 
  •  

Question

several times I wrote bits of code that would benefit from a "reverse" lock_guard, Like in this short example.

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
}

Is there a way to replace the inner unlock/lock by an automatic lock_guard in C++11 ?

Was it helpful?

Solution

You may write your own 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_;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top