Understanding FreeRTOS Task Scheduling and Communication

1. FreeRTOS Tasks

In most general-purpose operating systems (such as Linux, Windows, etc.), threads are the smallest unit of scheduling for the system, while processes are the smallest running processes for independent applications. In real-time operating systems, in most cases, there is no distinction between threads and processes for independent management. To reduce system resource usage and improve real-time performance, tasks are often used as the smallest unit of scheduling for applications, using TCB (Task Control Block) to manage tasks. As a commonly used RTOS, FreeRTOS follows the design principles of task scheduling and communication found in many RTOS. Its simple, convenient, and easy-to-use task mechanism is one of the reasons it has become the market leader in RTOS in recent years. This article mainly describes its task scheduling implementation and communication principles.

2. FreeRTOS Task Scheduling

After tasks in FreeRTOS are dynamically or statically created, they are not deleted. The current task states are Running, Ready, Blocked, and Suspended. From the task information and task state diagram provided by FreeRTOS, it can be seen that task scheduling is mainly divided into three stages:
Stage 1: Task Creation and Scheduler Startup Stage (blue part in the figure below)
Stage 2: After the task runs, it calls the task API or the scheduler arbitrates to switch task states (green part in the figure below)
Stage 3: Task Deletion and Destruction Stage (red part in the figure below)

Understanding FreeRTOS Task Scheduling and Communication

1. Task Creation and Startup Stage

FreeRTOS calls xTaskCreate (dynamic creation) or xTaskCreateStatic (static creation) API to create tasks. When dynamically creating tasks, memory for the task stack and task control block (TCB) is allocated, the allocated memory is initialized, the prvInitialiseNewTask function is called to initialize the task, and finally, the prvAddNewTaskToReadyList function is called to add the newly created task to the ready task list (as shown in the official code).

Understanding FreeRTOS Task Scheduling and Communication

After creating the task, the task API function vTaskStartScheduler is usually called immediately to start task scheduling. Taking the dynamic task creation method as an example, the vTaskStartScheduler function first creates the idle task, if using a software timer, it creates a software timer, disables interrupts, marks the scheduler as running, and if time statistics is enabled, it calls the xPortStartScheduler function (this function adapts to different hardware platforms, typically used to initialize hardware resources, tick timers, etc.; for example, the Cortex-M series initializes the FPU unit, tick timer, PendSV interrupt, etc.), as shown in the flow diagram below.

Understanding FreeRTOS Task Scheduling and Communication

2. Task Running Stage

After the scheduler starts, before the created task is deleted or destroyed, the task will switch between the Running, Ready, Blocked, and Suspended states.

The running task enters the blocked state when calling system delay functions (such as vTaskDelay function), waiting for notifications using ulTaskNotifyTake, or waiting for semaphores using xSemaphoreTake; a running task can suspend itself by waiting for resources or calling the vTaskSuspend interface; a running task can be interrupted by a higher priority task, entering the ready task queue.
Tasks in the blocked state will be awakened and re-enter the ready task list when the required resources are available or when the system wait time expires; additionally, a blocked task can also be suspended using the xSemaphoreTake interface.
Suspended tasks can only be restored to the ready queue by calling the system API interface vTaskResume function, and suspended tasks can only switch to the ready state.
Ready tasks enter the running state directly when the scheduler arbitrates and obtains CPU execution rights, and can use the vTaskSuspend interface to suspend themselves.
The switching between running and ready states in FreeRTOS mainly relies on the scheduler for arbitration, and the arbitration algorithm supports both priority preemption and time-slice scheduling (enabling configUSE_PORT_OPTIMISED_TASK_SELECTION=1).
The first method is the priority preemption method: FreeRTOS uses the vTaskSwitchContext system API function for task switching and calls the taskSELECT_HIGHEST_PRIORITY_TASK() function for arbitration to get the next task to run based on task priority; the prototype of the vTaskSwitchContext function is as follows:

Understanding FreeRTOS Task Scheduling and Communication

The second method is the time-slice round-robin scheduling method: After enabling time-slice round-robin, FreeRTOS provides the system API interface xTaskIncrementTick function for time-slice round-robin scheduling of tasks with the same priority. Each time slice size is generally equal to the tick timer interrupt cycle. In most cases, the xTaskIncrementTick function is called in the tick timer interrupt callback to determine whether to perform polling switching of tasks with the same priority (if a task finishes execution within a tick clock cycle, the portYIELD interface will be forcibly called to switch tasks and give up the remaining time slice). As shown in the figure below, TaskA has the same priority as TaskB, and the tick timer period is 1ms.

Understanding FreeRTOS Task Scheduling and Communication

3. Task Deletion and Destruction Stage

Ready, blocked, and suspended tasks can all call the vTaskDelete system API interface to delete themselves. The task control block (TCB) and task stack of the deleted task will be deleted and released in the idle task.

3. Task Communication

FreeRTOS provides several task communication methods common to general operating systems. The commonly used communication methods provided to users include: message queues, semaphores, mutexes (mutex semaphores), event flag groups, and task notifications.
FreeRTOS task notifications have a 32-bit message notification value, where only one task receives the notification, which can reduce RAM usage and is 45% faster than binary semaphores (according to official data).
The difference between event flag groups and semaphores is that event flag groups are mainly used for synchronization between a task and multiple events or synchronization between a task and multiple tasks.

1. Semaphores

FreeRTOS semaphores are primarily used for synchronization between a task and a single event or task. The commonly used semaphores in FreeRTOS include the following types:

a. Binary semaphore

b. Counting semaphore

c. Mutex semaphore

d. Recursive mutex semaphore

The following is a GIF demonstration of the basic working principle of binary semaphores provided by the official documentation:

Understanding FreeRTOS Task Scheduling and Communication

2. Message Queues

FreeRTOS message queues are primarily used for passing large amounts of messages between tasks. The following is a GIF demonstration of the basic working principle of message queues provided by the official documentation:

Understanding FreeRTOS Task Scheduling and Communication

4. Conclusion

FreeRTOS employs strong preemptive scheduling for tasks of different priorities (high-priority preemption) to maintain its unique real-time characteristics as an RTOS. Tasks with the same priority utilize time-slice round-robin scheduling to ensure equal opportunity for scheduling and execution. Communication between tasks is facilitated through semaphores, message queues, notifications, event flag groups, and other methods to ensure effective and efficient communication between interrupt events and tasks, as well as between tasks. Additionally, due to its unique free and open-source characteristics, its market share in the RTOS space continues to grow.
References

FreeRTOS official documentation: https://www.freertos.org/features.html

FreeRTOS official code: https://www.freertos.org/a00104.html

Understanding FreeRTOS Task Scheduling and Communication

Long press to follow
Kernel Craftsman WeChat
Linux Kernel Black Technology | Technical Articles | Selected Tutorials

Leave a Comment