Comparison of FreeRTOS Semaphores (Part Five)

Message queues/semaphores/mutexes can be further compared.

The following APIs seem well-organized(in fact, their underlying implementations come from the same source~)

QueueHandle_t xQueue = xQueueCreate(10, sizeof(int)); // Create a queuexQueueSend(xQueue, &data, portMAX_DELAY); // Send dataxQueueReceive(xQueue, &receivedData, portMAX_DELAY); // Receive data

SemaphoreHandle_t xSemaphore = xSemaphoreCreateBinary(); // Create a binary semaphore

xSemaphoreGive(xSemaphore); // Release the semaphore

xSemaphoreTake(xSemaphore, portMAX_DELAY); // Obtain the semaphore

SemaphoreHandle_t xMutex = xSemaphoreCreateMutex(); // Create a mutex

xSemaphoreTake(xMutex, portMAX_DELAY); // Obtain the mutex

xSemaphoreGive(xMutex); // Release the mutex

Summary Points

1. When creating a message queue, you must specify the size of the storage space, as it can hold more information. However, binary semaphores/mutexes only care about state and do not require additional data. Conversely, it is important to understand how a message queue retrieves data items and how counting semaphores obtain their count value.

2. Mutex semaphores have the advantage of supporting priority inversion.

3. Blocking is a state of task scheduling. Since tasks are recorded in a linked list, when a task is “blocked,” it is removed from the ready list, and the CPU no longer involves this task, thus saving load. When the semaphore is given, the corresponding task will return to the ready state, waiting for the next scheduling. This response delay is very short, and the use of semaphores greatly reduces system power consumption. Thegive and take of semaphores can be distributed across different tasks to achieve an event-driven effect. It can even be said that in most cases, semaphores are better than polling, unless the polling event occurs at a frequency lower than the instruction cycle of the task call.~

4. The blocking timeout, 0 means no timeout, while portMAX_DELAY means waiting indefinitely.(in tick clock units)

Four States of Task Scheduling

Running

Ready

Blocked: If a task enters a state due to delay or waiting for a semaphore/ message queue/ event flags, it is called a blocked state.

Suspended: The state of a task that is not executed after being suspended by calling vTaskSuspend() needs to be resumed by vTaskResume().

Self-Reflection

These are not difficult concepts to understand, but initially, it was hard to remember various APIs. After organizing them today, they are much easier to remember.

Leave a Comment