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 ?
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).
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.
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.
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.
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_;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With