0
0
FreeRTOSprogramming~5 mins

Time-slicing for equal priority tasks in FreeRTOS

Choose your learning style9 modes available
Introduction

Time-slicing lets tasks with the same priority share the CPU fairly by taking turns. This keeps your program responsive and balanced.

When you have multiple tasks that do different jobs but have the same importance.
When you want to make sure no single task hogs the CPU and others get a chance to run.
When tasks need to run smoothly without waiting too long for CPU time.
When you want to keep your system responsive even with many tasks running.
Syntax
FreeRTOS
vTaskStartScheduler();
// FreeRTOS automatically time-slices tasks of equal priority
// No special code needed to enable time-slicing

FreeRTOS automatically switches between tasks of the same priority every tick.

You just create tasks with the same priority; the scheduler handles the rest.

Examples
Two tasks with priority 2 will share CPU time equally by time-slicing.
FreeRTOS
xTaskCreate(Task1, "Task 1", 1000, NULL, 2, NULL);
xTaskCreate(Task2, "Task 2", 1000, NULL, 2, NULL);
vTaskStartScheduler();
Tasks A and B share CPU time by time-slicing because they have the same priority 1. Task C (priority 3) has higher priority and preempts A and B when ready.
FreeRTOS
xTaskCreate(TaskA, "Task A", 1000, NULL, 1, NULL);
xTaskCreate(TaskB, "Task B", 1000, NULL, 1, NULL);
xTaskCreate(TaskC, "Task C", 1000, NULL, 3, NULL);
vTaskStartScheduler();
Sample Program

This program creates two tasks with the same priority. FreeRTOS switches between them regularly, so both print their messages repeatedly.

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

void Task1(void *pvParameters) {
    for (;;) {
        printf("Task 1 running\n");
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

void Task2(void *pvParameters) {
    for (;;) {
        printf("Task 2 running\n");
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

int main(void) {
    xTaskCreate(Task1, "Task 1", 1000, NULL, 2, NULL);
    xTaskCreate(Task2, "Task 2", 1000, NULL, 2, NULL);
    vTaskStartScheduler();
    for(;;); // Should never reach here
    return 0;
}
OutputSuccess
Important Notes

Time-slicing depends on the tick interrupt frequency; faster ticks mean more frequent switches.

If tasks block or delay themselves, time-slicing pauses until they are ready again.

Tasks with higher priority run before time-slicing happens among equal priority tasks.

Summary

Time-slicing lets tasks of the same priority share CPU time fairly.

FreeRTOS handles time-slicing automatically; just assign equal priorities.

This keeps your system responsive and balanced when running multiple tasks.