获取两个互斥锁的锁,避免死锁 [英] Acquire a lock on two mutexes and avoid deadlock
问题描述
以下代码包含潜在的死锁,但似乎是必要的:要将数据安全地从另一个容器复制到一个容器,必须锁定这两个容器,以防止在另一个线程中发生更改。
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 changes from occurring in another thread.
void foo::copy(const foo & rhs)
{
pMutex->lock();
rhs.pMutex->lock();
// do copy
}
Foo有一个STL容器,复制基本上由使用std :: copy组成。
Foo has an STL container and "do copy" essentially consists of using std::copy. How do I lock both mutexes without introducing deadlock?
推荐答案
对的实例施加某种总排序, foo
并始终以递增或递减顺序获取它们的锁,例如, foo1-> lock()
然后 foo2-> lock()
。
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()
.
另一种方法是使用函数语义, c $ c> foo :: clone 方法创建一个新的实例,而不是破坏现有的实例。
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.
这篇关于获取两个互斥锁的锁,避免死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!