Wait for event bits
Decide whether a task waiting on an event group may run, and clear the bits it consumed. A medium embedded C problem (RTOS synchronisation), run and graded…
medium · RTOS synchronisation · rtos · event-group · bits
An event group is a word of flags that tasks and interrupts set. A task waits for some of them, given as mask:
- with
wait_allfalse, the wait is satisfied when any bit ofmaskis set; - with
wait_alltrue, it is satisfied only when every bit ofmaskis set.
Return whether the wait is satisfied. If it is and clear_on_exit is true, clear the bits of mask in the group (and only those). If it is not satisfied, leave the group unchanged. An empty mask is never satisfied.
Starter code
bool event_wait(event_group_t *g, uint32_t mask, bool wait_all, bool clear_on_exit) {
bool met = (g->bits & mask) != 0;
if (clear_on_exit) g->bits &= ~mask;
return met;
}Example tests
Wait for any bit
event_group_t g = { 0x05 };
bool a = event_wait(&g, 0x01, false, false);
printf("%d %02X\n", a, g.bits);
bool b = event_wait(&g, 0x03, false, true);
printf("%d %02X\n", b, g.bits);Expected output:
1 05
1 04Wait for all bits
event_group_t g = { 0x05 };
bool met = event_wait(&g, 0x03, true, false);
printf("%d %02X\n", met, g.bits);Expected output:
0 05Learn 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.
- 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.