
"Peter Dimov" <pdimov@pdimov.com> 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 it.
I like the idea, but surely the publicly-visible swap should lock both mutexes? Wouldn't this be better as internal_swap()? Anthony -- 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