I'm wondering if it's possible to lock multiple mutexes at the same time, like:
Mutex1.Lock(); { Mutex2.Lock(); { // Code locked by mutex 1 and 2. } Mutex2.Unlock(); // Code locked by mutex 1. } Mutex1.Unlock();
It would be very useful for some situations. Thanks.
Using Locking HierarchiesThere could be a problem if two threads attempt to claim both resources but lock the associated mutexes in different orders. For example, if the two threads lock mutexes 1 and 2 respectively, then a deadlock occurs when each attempts to lock the other mutex.
1. What will happen if a non-recursive mutex is locked more than once? Explanation: If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into the waiting list of that mutex, which results in a deadlock. It is because no other thread can unlock the mutex.
In our case, the deadlock happens when two threads are waiting for a mutex owned by the other. One of the most common ways of avoiding a deadlock is to always lock the two mutexes in the same order. If we always lock mutex A before mutex B, then we'll never have a deadlock.
There can be only one lock on a mutex at any given time. The thread holding the lock is the current owner of the mutex. If another thread wishes to gain control, it must wait for the first thread to unlock it. This mutual exclusion is the primary goal of the mutex, and indeed the origin of the name.
std::lock
seems to exist for this purpose.
Locks the given Lockable objects lock1, lock2, ..., lockn using a deadlock avoidance algorithm to avoid deadlock. The objects are locked by an unspecified series of calls to lock, try_lock, unlock. If a call to lock or unlock results in an exception, unlock is called for any locked objects before rethrowing.
http://en.cppreference.com/w/cpp/thread/lock
C++17 also provides scoped_lock
for the specific purpose of locking multiple mutexes that prevents deadlock in a RAII style, similar to lock_guard
.
#include<mutex> std::mutex mtx1, mtx2; void foo() { std::scoped_lock lck{mtx1, mtx2}; // proceed }
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