Acquire a lock on two mutexes and avoid deadlock

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

    Impose some kind of total order on instances of foo and always acquire their locks in either increasing or decreasing order, e.g., foo1->lock() and then foo2->lock().

    Another approach is to use functional semantics and instead write a foo::clone method that creates a new instance rather than clobbering an existing one.

    If your code is doing lots of locking, you may need a complex deadlock-avoidance algorithm such as the banker's algorithm.

提交回复
热议问题