Friday 26 June 2020

Multithreading:4.Deadlock

Suppose we want to protect our resource doubly and we introduce two mutex to guard the resource.
Here in the below code we are locking m1 first in thread t1 and m2 first in thread t2. Now to lock m2 in thread t1 it will be waiting for t2 to unlock, which never happens. That is a deadlock situation.

To avoid this situation

  • Prefer locking single mutex at a time 
  • Avoid locking a mutex and then calling a user provided function, because the user provided function might crash and we may never be able to unlock it. 
  • Use std::lock() to lock more than one mutex. 
  • Lock the mutex in same order.

No comments:

Post a Comment