Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

c++11

mutex

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 ?

like image 737
Ryp Avatar asked May 05 '14 08:05

Ryp


People also ask

Is lock_guard deprecated?

And the empty case should not lock anything. And that's why lock_guard isn't deprecated. scoped_lock and unique_lock may be a superset of functionality of lock_guard , but that fact is a double-edged sword. Sometimes it is just as important what a type won't do (default construct in this case).

What is the difference between unique_lock and lock_guard?

A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.

What is the role of std :: lock_guard?

std::lock_guard The class lock_guard is a mutex wrapper that provides a convenient RAII-style mechanism for owning a mutex for the duration of a scoped block. When a lock_guard object is created, it attempts to take ownership of the mutex it is given.

Does unique_lock automatically unlock?

look up how a unique_lock() behaves. @Prab, just to give the explanation: unique_lock() is automatically released when the destructor is called meaning it is exception safe and that it automatically unlocks when you leave scope.


1 Answers

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_;
};
like image 117
vz0 Avatar answered Nov 15 '22 16:11

vz0