Skip to content
BytePatterns

Deadlocked Threads in a Wait Graph

MediumConcurrency#wait-for-graph#cycle-detection~25m

Problem

A lock monitor takes a snapshot of a running process. holds maps each held lock to the thread holding it, and waits maps each blocked thread to the one lock it is waiting for; a thread waits for at most one lock at a time. A thread is deadlocked when following "waits for a lock held by" from it leads back to itself. Return the deadlocked threads, sorted. Threads that are merely stuck behind a deadlock, without being on the cycle themselves, are not part of the answer.

Examples

Input:  holds = {"a": "T1", "b": "T2"}, waits = {"T1": "b", "T2": "a"}
Output: ['T1', 'T2']
Why:    T1 waits for T2 and T2 waits for T1
Input:  holds = {"a": "T1", "b": "T2", "c": "T3"}, waits = {"T1": "b", "T2": "c", "T3": "a", "T4": "a"}
Output: ['T1', 'T2', 'T3']
Why:    T4 is blocked behind the cycle but not on it
Input:  holds = {"a": "T1"}, waits = {"T2": "a", "T3": "a"}
Output: []
Why:    edge case, T1 is running, so the waiters will get their turn

Hints

0 / 3

Stuck on the idea rather than the code? Detecting Deadlock covers it.