Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2007-07-20 18:15:30


Phillip Hellewell wrote:

> However, even the simplest _assignable_ class seems almost impossible
> to me to make thread-safe. You can synchronize operator= using both
> its own mutex(es) and rhs's mutex(es), which seems to solve the
> problem. But how do you prevent deadlock from something like this?
>
> Thread 1: x = y
> Thread 2: y = x
>
> Thread 2 is going to lock the mutexes in the opposite order of thread
> 1. Ouch!

The classic solution is to lock the mutexes in ascending order of their
addresses, but I prefer

X& X::operator=( X const& rhs )
{
    X tmp( rhs ); // temporarily locks rhs.mutex

    scoped_lock lock( this->mutex );
    swap( tmp ); // or move_from( tmp )

    return *this;
}

It's always a good idea to only lock one mutex at a time if you can afford
it.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk