Search code examples
c++thread-safetymutexboost-mutex

Holding two mutex locks at the same time


I would like to know if there would be any issue if I hold two boost::scoped_locks at the same time. The locks are locking different mutexes. Consider the following example:

void foo1()
{
   boost::recursive_mutex::scoped_lock lock(mutex1);
   foo2();
}

void foo2()
{
   boost::recursive_mutex::scoped_lock lock(mutex2);
}

I know that this shouldn't cause a deadlock. But are there any other issues. Maybe this could cause the thread to sleep for too long?


Solution

  • Holding more than one lock is not in itself a problem.

    Problems arise when other threads attempt to obtain those same locks in different order and you end up with ABBA deadlocks. Thread 1 locks A and B, then thread 2 wants to lock B then A and both end up being blocked (if the locking interleaves so t1 locks A, then t2 locks B and then both block trying to lock the other) waiting for the other to release one of the locks in order to be able to continue (and release their own held locks which would allow the other to continue).

    So, the general rule of thumb is; if you need to obtain more than one lock, make damn sure that all threads always attempt to aquire those locks in the same order.