线程和简单的死锁治疗

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

问题描述

在使用互斥锁和信号量处理线程(特别是在 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)