如何检测并发现程序处于死锁状态? [英] How to detect and find out a program is in deadlock?

查看:817
本文介绍了如何检测并发现程序处于死锁状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个面试问题.

如何检测并找出程序是否处于死锁状态?在Linux/Unix系统上是否可以使用某些工具来做到这一点?

How to detect and find out if a program is in deadlock? Are there some tools that can be used to do that on Linux/Unix systems?

我的想法:

如果程序没有任何进展并且其状态正在运行,则说明它处于死锁状态.但是,其他原因也会导致此问题.开源工具valgrind(halgrind)可以做到这一点.正确的?

If a program makes no progress and its status is running, it is deadlock. But, other reasons can also cause this problem. Open source tools are valgrind (halgrind) can do that. Right?

推荐答案

我建议您查看

这种问题的最简单示例如下.

The simplest example of such a problem is as follows.

想象一下某个共享资源R,无论出于何种原因,共享资源R都由两个锁L1和L2保护,当访问R时,这两个锁都必须同时保持.

Imagine some shared resource R, which, for whatever reason, is guarded by two locks, L1 and L2, which must both be held when R is accessed.

假定一个线程先获取L1,然后再获取L2,然后继续访问R.这意味着程序中的所有线程必须先按L1再按L2的顺序获取两个锁.否则可能会陷入僵局.

Suppose a thread acquires L1, then L2, and proceeds to access R. The implication of this is that all threads in the program must acquire the two locks in the order first L1 then L2. Not doing so risks deadlock.

如果两个线程(分别称为T1和T2)都想要访问R,则可能发生死锁.假设T1首先获取L1,而T2首先获取L2.然后,T1尝试获取L2,T2尝试获取L1,但是这些锁都已经被持有.因此T1和T2陷入僵局."

The deadlock could happen if two threads -- call them T1 and T2 -- both want to access R. Suppose T1 acquires L1 first, and T2 acquires L2 first. Then T1 tries to acquire L2, and T2 tries to acquire L1, but those locks are both already held. So T1 and T2 become deadlocked."

这篇关于如何检测并发现程序处于死锁状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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