Boost logo

Boost :

From: Anthony Williams (anthony_w.geo_at_[hidden])
Date: 2008-02-01 09:44:27

Kowalke Oliver (QD IT PA AS <Oliver.Kowalke <at>> writes:

> what's the best practice in following scenario:
> m threads and n resources (each resource is protected by a mutex)
> thread x needs read/write access to resources (...i,j,k,..)
> threads y,z,... do access another subset of resources at the same time
> inorder to protected deadlocks I would do following in the code of the
different threads (code executed by
> the threads are different):
> ...
> try_lock: // label
> unique_lock< mutex > lk1( mtx1, try_to_lock_t);
> unique_lock< mutex > lk4( mtx2, try_to_lock_t);
> unique_lock< mutex > lk7( mtx3, try_to_lock_t);
> if ( ! ( lk1 && lk2 && lk3) ) goto try_lock;
> // all mutexes are locked
> // now modify safely resource 1,2,3
> ...
> Maybe you have a better pattern do solve this problem?

I intended to write a lock template for this, but never got round to it.

There are two ways to solve the multiple lock problem: order the mutexes (e.g.
by address) so they are always locked in the same order, or do try-and-back-off,
one variant of which you showed above.

A better version of try-and-back-off is to lock the first mutex unconditionally,
and then try to lock the others in turn. If a lock fails, then unlock ALL the
mutexes and start again, but this time with a blocking lock on the failed mutex.
This means that you're waiting for the mutex that you couldn't get last time,
but without holding any others, so you won't deadlock with another thread.
There's a small possibility of livelock if two threads try this technique on
precisely the same set of mutexes at the same time, but it's unlikely to occur
in practice, and likely to resolve quickly if it does.


Anthony Williams            | Just Software Solutions Ltd
Custom Software Development |
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL

Boost list run by bdawes at, gregod at, cpdaniel at, john at