Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a simple timed lock algorithm avoiding deadlock on multiple mutexes?

C++0x thread library or Boost.thread define a non-member variadic template function that locks all mutex at once that helps to avoid deadlock.

template <class L1, class L2, class... L3> 
void lock(L1&, L2&, L3&...);

The same can be applied to a non-member variadic template function try_lock_until, which locks all the mutex until a given time is reached that helps to avoid deadlock like lock(...).

template <class Clock, class Duration,
          class L1, class L2, class... L3> 
void try_lock_until(
          const chrono::time_point<Clock,Duration>& abs_time, 
          L1&, L2&, L3&...);

I have an implementation that follows the same design as the Boost function boost::lock(...). But this is quite complex.

As I can be missing something evident I wanted to know if:

is there a simple timed lock algorithm avoiding deadlock on multiple mutexes?

If no simple implementation exists, can this justify a proposal to Boost?

P.S. Please avoid posting complex solutions.


Notes:

  1. I don't want to add more constraints than the ones std::lock(...) imposes.
  2. std::lock(...) doesn't avoid deadlock completely. It just avoid to have dead lock if two threads do std::lock(l1,l2) and the other std::lock(l2,l1). This is enough to avoid a lot of deadlock cases.
like image 261
Vicente Botet Escriba Avatar asked Oct 29 '25 05:10

Vicente Botet Escriba


1 Answers

The classic (and best) approach is to define an order in which mutexes are to be locked, and make sure that any code that holds more than one locked mutex at a time always locks its mutexes in that order. Is that approach insufficient here?

like image 94
Jeremy Friesner Avatar answered Oct 30 '25 22:10

Jeremy Friesner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!