Acquire a lock on two mutexes and avoid deadlock

前端 未结 6 1192
清歌不尽
清歌不尽 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:49

    How about this?

    void foo::copy(const foo & rhs)
    {
        scopedLock lock(rhs.pMutex); // release mutex in destructor
        foo tmp(rhs);
        swap(tmp); // no throw swap locked internally
    }
    

    This is exception safe, and pretty thread safe as well. To be 100% thread save you'll need to review all code path and than re-review again with another set of eyes, after that review it again...

提交回复
热议问题