Graceful shutdown sequence in FreeRTOS - Time & Space Complexity
When we stop a FreeRTOS system carefully, we want to know how long it takes as the number of tasks grows.
We ask: How does the shutdown time change when there are more tasks to stop?
Analyze the time complexity of the following code snippet.
void gracefulShutdown(void) {
for (int i = 0; i < numTasks; i++) {
vTaskDelete(taskHandles[i]);
}
// Additional cleanup here
}
This code stops each running task one by one to shut down the system safely.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over all tasks to delete each one.
- How many times: Exactly once per task, so
numTaskstimes.
As the number of tasks grows, the time to stop them grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 task deletions |
| 100 | 100 task deletions |
| 1000 | 1000 task deletions |
Pattern observation: Doubling the tasks doubles the shutdown steps.
Time Complexity: O(n)
This means the shutdown time grows directly with the number of tasks to stop.
[X] Wrong: "Stopping all tasks happens instantly, no matter how many there are."
[OK] Correct: Each task must be stopped one by one, so more tasks mean more work and more time.
Understanding how shutdown time grows helps you design systems that stop safely and predictably, a skill valued in real projects.
"What if tasks could be stopped in parallel instead of one by one? How would the time complexity change?"