Acquire a lock on two mutexes and avoid deadlock

前端 未结 6 1148
清歌不尽
清歌不尽 2021-01-04 13:04

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

6条回答
  •  花落未央
    2021-01-04 13:52

    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
    }
    

提交回复
热议问题