线程和简单死锁治疗 [英] Threads and simple Dead lock cure

查看:167
本文介绍了线程和简单死锁治疗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当处理线程(特别是在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. 死锁

  1. Thread 1 locks resource A
  2. Thread 2 locks resource B
  3. Thread 1 waits to obtain a lock on B
  4. Thread 2 waits to obtain a lock on A
  5. Deadlock

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

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.

这篇关于线程和简单死锁治疗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆