线程和简单的死锁治疗

在使用互斥锁和信号量处理线程(特别是在 C++ 中)时,是否有一个简单的经验法则可以避免死锁并实现干净的同步?

When dealing with threads (specifically in C++) using mutex locks and semaphores is there a simple rule of thumb to avoid Dead Locks and have nice clean Synchronization?

推荐答案

一个好的简单经验法则是始终以一致的可预测顺序从应用程序的任何位置获取锁.例如,如果您的资源有名称,请始终按字母顺序锁定它们.如果他们有数字 id,请始终从最低到最高锁定.确切的顺序或标准是任意的.关键是要保持一致.这样你就永远不会陷入僵局.例如.

A good simple rule of thumb is to always obtain your locks in a consistent predictable order from everywhere in your application. For example, if your resources have names, always lock them in alphabetical order. If they have numeric ids, always lock from lowest to highest. The exact order or criteria is arbitrary. The key is to be consistent. That way you'll never have a deadlock situation. eg.

  1. 线程 1 锁定资源 A
  2. 线程 2 锁定资源 B
  3. 线程 1 等待获得 B 上的锁
  4. 线程 2 等待获取 A 上的锁
  5. 死锁

如果您遵循上述经验法则,上述情况永远不会发生.如需更详细的讨论,请参阅维基百科关于餐饮哲学家问题的条目.

The above can never happen if you follow the rule of thumb outlined above. For a more detailed discussion, see the Wikipedia entry on the Dining Philosophers problem.

相关文章