Skip to content
Advertisement

How to detect and find out a program is in deadlock?

This is an interview question.

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?

My idea:

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?

Advertisement

Answer

I would suggest you look at Helgrind: a thread error detector.

The simplest example of such a problem is as follows.

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.

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.

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.”

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement