Multiple tasks running concurrently in FreeRTOS - Time & Space Complexity
When multiple tasks run at the same time in FreeRTOS, it's important to understand how the total work grows as we add more tasks.
We want to know how the time to manage all tasks changes when the number of tasks increases.
Analyze the time complexity of the following code snippet.
void vTask1(void *pvParameters) {
while(1) {
// Task 1 work
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
void vTask2(void *pvParameters) {
while(1) {
// Task 2 work
vTaskDelay(100 / portTICK_PERIOD_MS);
}
}
int main() {
xTaskCreate(vTask1, "Task1", 1000, NULL, 1, NULL);
xTaskCreate(vTask2, "Task2", 1000, NULL, 1, NULL);
vTaskStartScheduler();
return 0;
}
This code creates two tasks that run repeatedly and share CPU time managed by FreeRTOS.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Each task runs an infinite loop doing work and then delaying.
- How many times: Each task repeats its loop forever, switching happens many times.
As we add more tasks, the scheduler must switch between them more often, increasing the total management work.
| Number of Tasks (n) | Approx. Scheduler Operations |
|---|---|
| 2 | Low switching overhead |
| 10 | More frequent context switches |
| 100 | Much more switching and management |
Pattern observation: The scheduler's work grows roughly in proportion to the number of tasks.
Time Complexity: O(n)
This means the time to manage all tasks grows linearly as we add more tasks.
[X] Wrong: "Adding more tasks won't affect performance because tasks run independently."
[OK] Correct: The scheduler must switch between all tasks, so more tasks mean more switching and overhead.
Understanding how task management scales helps you design efficient multitasking systems and shows you grasp real-time system behavior.
"What if tasks had different priorities? How would that affect the time complexity of scheduling?"