Counting semaphore
Implement non-blocking take and give for a semaphore with a maximum count. An easy embedded C problem (RTOS synchronisation), run and graded in the browser.
easy · RTOS synchronisation · rtos · semaphore
A counting semaphore holds up to max tokens. Implement the non-blocking versions of its two operations:
csem_taketakes a token and returnstrue, or returnsfalseif there are none.csem_givereturns a token and returnstrue, or returnsfalseif the semaphore is already full.
Starter code
bool csem_take(csem_t *s) {
s->count--;
return true;
}
bool csem_give(csem_t *s) {
s->count++;
return true;
}Example tests
Give up to the maximum
csem_t s = { 0, 3 };
ops(&s, "gggg");Expected output:
1110 3Take until empty
csem_t s = { 2, 3 };
ops(&s, "ttt");Expected output:
110 0Learn it first
- RTOS synchronisation primitives · Mutexes, semaphores, queues, event flags and priority inversion.
More RTOS synchronisation problems
- 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.
- Detect a deadlock · Find a cycle of tasks each waiting for a mutex another one holds.