Priority inheritance
Make a mutex boost its owner's priority while a higher-priority task waits. A medium embedded C problem (RTOS synchronisation), run and graded in the browser.
medium · RTOS synchronisation · rtos · mutex · priority-inversion
Priority inversion happens when a low-priority task holds a mutex that a high-priority task needs, and medium-priority tasks keep the low one from running. Priority inheritance fixes it by lending the waiter's priority to the owner.
mutex_lock(m, t): if the mutex is free,tbecomes its owner and the call returnstrue. Otherwisetwould block: ift's effective priority is higher than the owner's, raise the owner's effective priority to match, then returnfalse.mutex_unlock(m): the owner's effective priority returns to its base priority, and the mutex becomes free.
A task holds at most one mutex here.
Starter code
bool mutex_lock(mutex_t *m, task_t *t) {
if (m->owner) return false;
m->owner = t;
return true;
}
void mutex_unlock(mutex_t *m) {
m->owner = NULL;
}Example tests
A high-priority waiter boosts the owner
task_t low = { 1, 1 }, high = { 5, 5 };
mutex_t m = { NULL };
bool a = mutex_lock(&m, &low);
bool b = mutex_lock(&m, &high);
printf("%d %d %u\n", a, b, low.effective);Expected output:
1 0 5Unlocking restores the base priority
task_t low = { 1, 1 }, high = { 5, 5 };
mutex_t m = { NULL };
mutex_lock(&m, &low);
mutex_lock(&m, &high);
mutex_unlock(&m);
printf("%u %d\n", low.effective, m.owner == NULL);Expected output:
1 1Learn 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.
- 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.
- Detect a deadlock · Find a cycle of tasks each waiting for a mutex another one holds.