The following code contains a potential deadlock, but seems to be necessary: to safely copy data to one container from another, both containers must be locked to prevent changes from occurring in another thread.
void foo::copy(const foo & rhs)
{
pMutex->lock();
rhs.pMutex->lock();
// do copy
}
Foo has an STL container and “do copy” essentially consists of using std::copy. How do I lock both mutexes without introducing deadlock?
Impose some kind of total order on instances of
fooand always acquire their locks in either increasing or decreasing order, e.g.,foo1->lock()and thenfoo2->lock().Another approach is to use functional semantics and instead write a
foo::clonemethod that creates a new instance rather than clobbering an existing one.If your code is doing lots of locking, you may need a complex deadlock-avoidance algorithm such as the banker’s algorithm.