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
To avoid a deadlock its probably best, to wait until both resources can be locked:
Dont know which mutex API you are using so here is some arbitrary pseudo code, assume that can_lock()
only checks if it can lock a mutex, and that try_lock()
returns true if it did lock, and false, if the mutex is already locked by somebody else.
void foo::copy(const foo & rhs)
{
for(;;)
{
if(! pMutex->cany_lock() || ! rhs.pMutex->cany_lock())
{
// Depending on your environment call or dont call sleep()
continue;
}
if(! pMutex->try_lock())
continue;
if(! rhs.pMutex->try_lock())
{
pMutex->try_lock()
continue;
}
break;
}
// do copy
}