问题描述
多线程应用程序冻结。也许是死锁造成的。如果是,那么我们如何找到导致死锁的原因呢?
A multi threaded application freezes. Perhaps it was caused by a deadlock. If yes, then how do we find the cause for the deadlock ? Any tools and strategies for doing this systematically ?
推荐答案
-
尽可能使用锁如这样的自由数据结构。根据定义,无锁数据结构不会导致死锁。
When possible, use a lock-free data structure like a ConcurrentLinkedQueue. By definition, a lock-free data structure cannot cause a deadlock.
始终以相同的顺序获取锁。如果你的资源是A,B和C,那么所有线程都应该按照A - > B - > C,或A - > C或B - > C等顺序获取它们。如果一个线程获取它们在顺序A - > B - > C中,而另一个线程按顺序C - > B - > A获取它们。
Always acquire locks in the same order. If your resources are A, B, and C, then all threads should acquire them in the order of A -> B -> C, or A -> C, or B -> C, etc. Deadlock can occur if one thread acquires them in the order A -> B -> C while another thread acquires them in the order C -> B -> A.
使用锁定超时 - if一个定时器超时,线程释放它的锁。
Use lock timeouts - if a timer expires then a thread releases its locks. Be sure to log when this occurs so that you can re-examine your lock ordering.
。
这篇关于找到多线程中死锁的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!