Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking multiple mutexes

Tags:

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.

like image 837
grimgrom Avatar asked Nov 20 '12 23:11

grimgrom


People also ask

Can a thread lock multiple mutexes?

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.

Can a mutex be locked more than once?

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.

How many mutexes does it take for a deadlock?

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.

How many mutexes can you have?

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.


2 Answers

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

like image 91
Pubby Avatar answered Sep 20 '22 08:09

Pubby


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 } 
like image 29
Passer By Avatar answered Sep 18 '22 08:09

Passer By