Simvik

Detect a deadlock

Find a cycle of tasks each waiting for a mutex another one holds. A hard embedded C problem (RTOS synchronisation), run and graded in the browser.

hard · RTOS synchronisation · rtos · deadlock · graphs

A deadlock is a cycle: task 0 waits for a mutex held by task 1, which waits for a mutex held by task 0. A debug monitor can find it from two tables:

  • owner[m] is the task holding mutex m, or -1 if it is free (n_mutex mutexes).
  • waits_for[t] is the mutex task t is blocked on, or -1 if it is not waiting (n_task tasks).

has_deadlock returns true if following "waits for a mutex, held by a task" from some task leads back to that task. A task waiting for a mutex it holds itself is a deadlock too.

Starter code

bool has_deadlock(const int8_t *owner, int n_mutex, const int8_t *waits_for, int n_task) {
  for (int t = 0; t < n_task; t++)
    if (waits_for[t] >= 0) return true;
  return false;
}

Example tests

Two tasks, two mutexes, the classic deadlock

const int8_t owner[] = { 0, 1 }, waits[] = { 1, 0 };
printf("%d\n", has_deadlock(owner, 2, waits, 2));

Expected output:

1

Waiting, but the chain ends

const int8_t owner[] = { 0, 1 }, waits[] = { 1, -1 };
printf("%d\n", has_deadlock(owner, 2, waits, 2));

Expected output:

0

Learn it first

More RTOS synchronisation problems

  • Counting semaphore · Implement non-blocking take and give for a semaphore with a maximum count.
  • Wait for event bits · Decide whether a task waiting on an event group may run, and clear the bits it consumed.
  • Priority inheritance · Make a mutex boost its owner's priority while a higher-priority task waits.
  • Recursive mutex · A mutex the owning task may take again, released only when every take is given back.
  • Message queue · A fixed-size queue that copies whole messages in and out, like an RTOS queue.