Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 259
Petko Six Avatar asked Jul 20 '16 19:07

Petko Six


1 Answers

This can cause a deadlock if anyone acquires both mutexes in the opposite order.

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

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

Two threads interleaved as follows will deadlock:

                                 mutex1  mutex2
Time    Thread A     Thread B    owner   owner
  0     foo1()                     A
  1                  bar1()        A       B
  2                  bar2()        A       B
  3     foo2()                     A       B

At this point threads A & B are deadlocked. I don't think that boost provides protection against this though the underlying OS may.

like image 178
D.Shawley Avatar answered Sep 21 '22 21:09

D.Shawley