0
0
FreeRTOSprogramming~5 mins

Preemptive scheduling behavior in FreeRTOS

Choose your learning style9 modes available
Introduction

Preemptive scheduling lets the system switch tasks automatically to keep things running smoothly. It helps important tasks get CPU time right away.

When you want your program to respond quickly to important events.
When multiple tasks need to run and some are more urgent than others.
When you want to make sure no single task blocks others for too long.
When you need real-time behavior in embedded systems like robots or sensors.
Syntax
FreeRTOS
void vTaskStartScheduler( void );

// Tasks are created with xTaskCreate(), specifying priority.
// Higher priority tasks preempt lower priority ones automatically.

Preemptive scheduling is enabled by default in FreeRTOS.

Task priorities determine which task runs first.

Examples
Task1 has higher priority (2) than Task2 (1), so Task1 runs first and can preempt Task2.
FreeRTOS
xTaskCreate(Task1, "Task 1", 1000, NULL, 2, NULL);
xTaskCreate(Task2, "Task 2", 1000, NULL, 1, NULL);
vTaskStartScheduler();
Tasks with the same priority share CPU time in a round-robin way.
FreeRTOS
xTaskCreate(TaskA, "Task A", 1000, NULL, 3, NULL);
xTaskCreate(TaskB, "Task B", 1000, NULL, 3, NULL);
vTaskStartScheduler();
Sample Program

This program creates two tasks. The high priority task will run first and preempt the low priority task when it wakes up, resulting in alternating output messages.

FreeRTOS
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>

void TaskHighPriority(void *pvParameters) {
    for (;;) {
        printf("High priority task running\n");
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

void TaskLowPriority(void *pvParameters) {
    for (;;) {
        printf("Low priority task running\n");
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

int main(void) {
    xTaskCreate(TaskLowPriority, "LowPriority", 1000, NULL, 1, NULL);
    xTaskCreate(TaskHighPriority, "HighPriority", 1000, NULL, 2, NULL);
    vTaskStartScheduler();
    for(;;); // Should never reach here
    return 0;
}
OutputSuccess
Important Notes

Preemptive scheduling helps keep your system responsive.

Make sure high priority tasks do not run forever, or lower priority tasks may starve.

Use vTaskDelay or similar to let other tasks run.

Summary

Preemptive scheduling lets higher priority tasks interrupt lower ones automatically.

It is useful for real-time and responsive systems.

Task priorities control which task runs first.