Boost logo

Boost :

From: dizzy (dizzy_at_[hidden])
Date: 2008-02-01 08:27:30

On Friday 01 February 2008 14:21:40 Kowalke Oliver (QD IT PA AS) wrote:
> Hi,
> 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?

Im not sure if it solves exactly your problem but generally needing to lock 2
mutexes for a given resource has the problem that it may very easily run into
deadlock situations if another thread tries to lock the same mutexes in the
reversed order. As such all you need to do is define an order relation across
the mutexes (good choices for such an order is order the locks by the mutexes
addresses in memory, this should provide you a complete strict order relation
across all mutexes that may be used at some moment).

I'm not sure what your example is suposed to do, is it suposed to be a trylock
or a normal lock (I supose that's what "try_to_lock_t" signals)? If it is a
trylock then you just described a busy wait loop (will consume 100% CPU
resources waiting for a lock). You just need to use normal blocking locks
expect you should be careful about order of locks to be always the same for
the same set of mutexes (as I described above). In my code (I needed often to
lock 2 mutexes) I have made a lock wrapper class that does the ordered
locking of the 2 mutexes.

Mihai RUSU					Email: dizzy_at_[hidden]
			"Linux is obsolete" -- AST

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