</>EmbeddedInterview

What are event groups / event flags?

MediumRTOS & Real-Time Systems

Short answer: An event group is a set of bits (flags) that tasks can set, clear and wait on with AND ("wait until bits 0 and 2 are both set") or OR ("wait until any of bits 0–3 is set") semantics, optionally clearing them on exit. They synchronise a task with several conditions at once, or several tasks at a barrier (xEventGroupSync). Unlike a counting semaphore, setting a bit that is already set does not count twice.

#define EV_WIFI_UP   (1u << 0)
#define EV_TIME_SYNC (1u << 1)
#define EV_CERT_OK   (1u << 2)

EventGroupHandle_t sys_events = xEventGroupCreate();

/* cloud task waits until all three are ready */
EventBits_t bits = xEventGroupWaitBits(sys_events,
                                       EV_WIFI_UP | EV_TIME_SYNC | EV_CERT_OK,
                                       pdFALSE,          /* do not clear on exit */
                                       pdTRUE,           /* wait for ALL bits */
                                       pdMS_TO_TICKS(30000));
if ((bits & (EV_WIFI_UP | EV_TIME_SYNC | EV_CERT_OK)) != (EV_WIFI_UP | EV_TIME_SYNC | EV_CERT_OK)) {
    /* timeout: handle */
}

Uses: system start-up readiness (network up, time synced), state broadcasts to several tasks, barriers in multi-step pipelines, and waiting for one of several sources.

Details and pitfalls

  • Several tasks can wait on the same group, and setting bits can unblock all of them (a broadcast), which semaphores cannot do.
  • Setting bits from an ISR (xEventGroupSetBitsFromISR) is deferred to the timer service task in FreeRTOS, because waking an unknown number of tasks is not a bounded operation; that adds latency.
  • Because bits are not counted, two events of the same type before the task runs merge into one. If you must count, use a semaphore or queue.
  • The number of usable bits is limited (24 with 32-bit ticks in FreeRTOS).

Zephyr: k_event (event objects) and k_poll for waiting on multiple kernel objects.