Topics / Data Structures & Algorithms / Q28
Detect a deadlock using a wait-for graph.
Short answer: Create an edge A→B if thread A waits for a resource exclusively held by thread B. A directed cycle indicates deadlock in the single-instance blocking resource model.
#include <stdbool.h>
#define N 8
static bool visit(const bool g[N][N], int u, int state[N])
{
state[u] = 1; /* visiting */
for (int v = 0; v < N; v++) {
if (!g[u][v]) continue;
if (state[v] == 1) return true;
if (state[v] == 0 && visit(g, v, state)) return true;
}
state[u] = 2; /* completed */
return false;
}
bool deadlock(const bool wait[N][N])
{
int state[N] = {0};
for (int i = 0; i < N; i++)
if (state[i] == 0 && visit(wait, i, state))
return true;
return false;
}
If T0 waits for T1 and T1 waits for T0, a cycle exists. Take a consistent graph snapshot; timeouts, multiple interchangeable resource instances and alternative acquisition conditions require more analysis. Time O(N²) with a matrix, O(V+E) with adjacency lists.