Recursive mutex
A mutex the owning task may take again, released only when every take is given back. A medium embedded C problem (RTOS synchronisation), run and graded in…
medium · RTOS synchronisation · rtos · mutex
A function that takes a mutex and calls another function that takes the same mutex would deadlock on itself with a plain mutex. A recursive mutex lets its owner take it again.
rmutex_take(m, task): if the mutex is free,taskbecomes the owner with depth 1. Iftaskalready owns it, the depth goes up by one (but never past 255: then fail). If another task owns it, fail. Return whether it succeeded.rmutex_give(m, task): only the owner may give. Each give lowers the depth; at 0 the mutex is free again (owner = NO_TASK). Return whether it succeeded.
Tasks are numbered from 1.
Starter code
bool rmutex_take(rmutex_t *m, uint8_t task) {
if (m->owner != NO_TASK) return false;
m->owner = task;
return true;
}
bool rmutex_give(rmutex_t *m, uint8_t task) {
m->owner = NO_TASK;
return true;
}Example tests
Nested takes by one task
rmutex_t m = { NO_TASK, 0 };
ops(&m, "t1t1t2g1g1t2");Expected output:
110111 2 1Only the owner may give
rmutex_t m = { NO_TASK, 0 };
ops(&m, "g1t1g2g1");Expected output:
0101 0 0Learn it first
- RTOS synchronisation primitives · Mutexes, semaphores, queues, event flags and priority inversion.
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.
- Message queue · A fixed-size queue that copies whole messages in and out, like an RTOS queue.
- Detect a deadlock · Find a cycle of tasks each waiting for a mutex another one holds.