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
As @Mellester mentioned you can use std::lock
for locking multiple mutexes avoiding deadlock.
#include
void foo::copy(const foo& rhs)
{
std::lock(pMutex, rhs.pMutex);
std::lock_guard l1(pMutex, std::adopt_lock);
std::lock_guard l2(rhs.pMutex, std::adopt_lock);
// do copy
}
But note to check that rhs
is not a *this
since in this case std::lock
will lead to UB due to locking same mutex.