Acquire a lock on two mutexes and avoid deadlock

前端 未结 6 1180
清歌不尽
清歌不尽 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 14:00

    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.

提交回复
热议问题