From: Anthony Williams (anthony_w.geo_at_[hidden])
Date: 2007-07-23 03:53:08
"Peter Dimov" <pdimov_at_[hidden]> writes:
> 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
I like the idea, but surely the publicly-visible swap should lock both
mutexes? Wouldn't this be better as internal_swap()?
-- Anthony Williams Just Software Solutions Ltd - http://www.justsoftwaresolutions.co.uk Registered in England, Company Number 5478976. Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk