Queues and event groups: tasks talking to each other
Pass data through a queue instead of global variables, and wait for several conditions at once with an event group.
Queue
A FIFO that passes data by copying it. When the queue is empty the receiving task sleeps, and it wakes when data arrives.
typedef struct { int16_t ax, ay, az; } imu_t;
QueueHandle_t q = xQueueCreate(8, sizeof(imu_t));
// producer
xQueueSend(q, &sample, 0);
// consumer
imu_t s;
if (xQueueReceive(q, &s, pdMS_TO_TICKS(10)) == pdTRUE) { /* process */ }
- There is less room for mistakes than with a global variable plus a mutex.
- Copying large data is expensive, so pass a pointer or a buffer index and make ownership clear.
- Decide what happens when it is full: drop, wait or overwrite.
Event group
A bundle of flags made of several bits. You can wait for several conditions together, such as "IMU ready and GPS ready", or wake when any one arrives.
RoadmapSee where this note sits in RTOS→Task notification
In FreeRTOS, when you send one signal or one value to one specific task, a task notification is faster than a semaphore and uses less memory.
How to choose
| Need | Tool |
|---|---|
| Passing data | Queue |
| A single "something happened" signal | Task notification, binary semaphore |
| A combination of conditions | Event group |
| Exclusive use of a resource | Mutex |