Concurrency · 14 / 15 Exercise Hard

Deadlock risk

Objective

A deadlock happens when two threads wait forever: each one holds a lock the other one needs. It can be detected in advance: if there is a cycle in the order in which threads ask for locks, there is a risk. Real threads cannot be created in the browser, so the program simulates the situation in a deterministic way.

Instructions

  • Read n and then n lines with thread lock1 lock2 ...: the name of a thread and the locks it asks for in that order, without releasing the previous ones.
  • Build a directed graph: there is an edge A → B if some thread asks for B (afterwards, without releasing it) while already holding A, that is, if in its list A appears before B.
  • Look for a cycle with a depth-first search (DFS) that goes through the nodes and the neighbors in alphabetical order. If there is one, show Possible deadlock: A -> B -> A with the cycle, starting and ending at the same lock.
  • If there is no cycle, show No deadlock risk.
Input
2
t1 L1 L2 L3
t2 L3 L1
Output
Possible deadlock: L1 -> L2 -> L3 -> L1

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise