If enabled, OS_IdleTask()
is the very first task created by µC/OS-III and always exists in a µC/OS-III-based application. The priority of the idle task is always set to OS_CFG_PRIO_MAX-1
. In fact, OS_IdleTask()
is the only task that is ever allowed to be at this priority and, as a safeguard, when other tasks are created, OSTaskCreate()
ensures that there are no other tasks created at the same priority as the idle task. The idle task runs whenever there are no other tasks that are ready-to-run.
If RAM space is tight, the idle task can be removed. This allows the user to save some data space since there is no need to have a stack for the idle task. However, even if there is not an actual task running at priority OS_CFG_PRIO_MAX-1
, the user cannot create a task at that priority level. The level is still used to determine when to idle the CPU.
The important portions of the code for the idle task are shown below (refer to os_core.c
for the complete code). These portions are still executed even if the idle task is disabled in os_cfg.h
.
Anchor | ||||
---|---|---|---|---|
|
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
void OS_IdleTask (void *p_arg)
{
while (DEF_ON) { (1)
CPU_CRITICAL_ENTER();
OSIdleTaskCtr++; (2)
OSStatTaskCtr++;
CPU_CRITICAL_EXIT();
OSIdleTaskHook(); (3)
}
} |
Panel | ||
---|---|---|
| ||
(1) The idle task is a “true” infinite loop that never calls functions to “wait for an event”. This is because, on most processors, when there is “nothing to do,” the processor still executes instructions. When µC/OS-III determines that there is no other higher-priority task to run, µC/OS-III “parks” the CPU in the idle task. However, instead of having an empty “infinite loop” doing nothing, µC/OS-III uses this “idle” time to do something useful. (2) Two counters are incremented whenever the idle task runs.
(3) Every time through the loop,
Typically, most processors exit low-power mode when an interrupt occurs. Depending on the processor, however, the Interrupt Service Routine (ISR) may have to write to “special” registers to return the CPU to its full or desired speed. If the ISR wakes up a high-priority task (every task is higher in priority than the idle task) then the ISR will not immediately return to the interrupted idle task, but instead switch to the higher-priority task. When the higher-priority task completes its work and waits for its event to occur, µC/OS-III causes a context switch to return to |