Consider two FreeRTOS tasks: TaskA with priority 2 and TaskB with priority 3. Both tasks are ready to run at the same time. TaskA starts running first. What happens next?
void TaskA(void *pvParameters) {
for (;;) {
// TaskA code
}
}
void TaskB(void *pvParameters) {
for (;;) {
// TaskB code
}
}
int main() {
xTaskCreate(TaskA, "TaskA", 1000, NULL, 2, NULL);
xTaskCreate(TaskB, "TaskB", 1000, NULL, 3, NULL);
vTaskStartScheduler();
return 0;
}Remember, in preemptive scheduling, the highest priority ready task runs immediately.
FreeRTOS uses preemptive scheduling. When a higher priority task becomes ready, it preempts the currently running lower priority task immediately.
In FreeRTOS, if a running task calls vTaskDelay(), what happens to the CPU scheduling?
void TaskExample(void *pvParameters) {
for (;;) {
// Do some work
vTaskDelay(pdMS_TO_TICKS(100));
}
}Think about what happens when a task delays itself in FreeRTOS.
Calling vTaskDelay() blocks the task for the specified time, allowing the scheduler to run other ready tasks.
Two tasks, Task1 and Task2, have the same priority in FreeRTOS. Both are ready to run. What is the expected behavior?
void Task1(void *pvParameters) {
for (;;) {
// Task1 code
}
}
void Task2(void *pvParameters) {
for (;;) {
// Task2 code
}
}
int main() {
xTaskCreate(Task1, "Task1", 1000, NULL, 2, NULL);
xTaskCreate(Task2, "Task2", 1000, NULL, 2, NULL);
vTaskStartScheduler();
return 0;
}Consider how FreeRTOS handles tasks with the same priority.
FreeRTOS uses time slicing (if configUSE_TIME_SLICING is enabled) to share CPU time fairly among tasks of equal priority.
In FreeRTOS, an interrupt service routine (ISR) makes a higher priority task ready to run. What happens immediately after the ISR completes?
void vAnISR(void) {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
xTaskNotifyFromISR(xHighPriorityTaskHandle, 0, eNoAction, &xHigherPriorityTaskWoken);
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}Think about how FreeRTOS handles context switches triggered by ISRs.
Using portYIELD_FROM_ISR() causes an immediate context switch to the higher priority task after the ISR ends.
In a FreeRTOS system, TaskLow (priority 1) holds a mutex needed by TaskHigh (priority 3). TaskMedium (priority 2) is ready to run. What problem can occur and how does FreeRTOS help prevent it?
Think about what happens when a low priority task blocks a high priority task and a medium priority task runs.
Priority inversion happens when a low priority task holds a resource needed by a high priority task. FreeRTOS uses priority inheritance to raise the low priority task's priority temporarily to prevent medium priority tasks from blocking progress.