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 cha
Impose some kind of total order on instances of foo
and always acquire their locks in either increasing or decreasing order, e.g., foo1->lock()
and then foo2->lock()
.
Another approach is to use functional semantics and instead write a foo::clone
method 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.