What Does the CPU Do When an RTOS Has No Ready Tasks?
When an RTOS has no runnable tasks and all tasks are delayed or waiting for events, the CPU does not stay idle but executes the system's idle task or thread, which may simply loop forever unless the developer adds custom work.
In a bare‑metal program the CPU is stuck in an infinite while(1) loop, continuously executing the same code. For example:
int main(void)
{
/* 初始化 */
while(1)
{
/* 循环处理多项事情 */
}
}When a real‑time operating system (RTOS) is introduced, the goal is to improve CPU utilization by running multiple independent tasks, each typically containing its own infinite loop:
void Task1(void)
{
/* 初始化 */
while(1)
{
/* 处理事情1 */
}
}
void Task2(void)
{
/* 初始化 */
while(1)
{
/* 处理事情2 */
}
}
/* … more tasks such as Task3, Task4, … */If all tasks are blocked—e.g., by vTaskDelay or waiting on a queue—the CPU does not simply stop. The RTOS schedules its built‑in idle task (or idle thread/process). This idle task runs whenever no higher‑priority task is ready.
On a typical desktop OS you can see a high‑CPU‑usage process called “System Idle Process”. In embedded RTOSes the same concept exists. For example, in uC/OS the idle task is named OS_TaskIdle, and in FreeRTOS it is called prvIdleTask.
uC/OS idle task: OS_TaskIdle FreeRTOS idle task: prvIdleTask The idle task often contains only a tight loop, optionally calling a user‑definable hook. A typical uC/OS idle implementation looks like:
void OS_TaskIdle(void *p_arg)
{
#if OS_CRITICAL_METHOD == 3u
/* Allocate storage for CPU status register */
#endif
OS_CPU_SR cpu_sr = 0u;
p_arg = p_arg; /* Prevent compiler warning */
for (;;)
{
OS_ENTER_CRITICAL();
OSIdleCtr++;
OS_EXIT_CRITICAL();
OSTaskIdleHook(); /* User‑definable hook */
}
}By default the hook does nothing, so the idle task essentially does nothing useful. Developers can add custom work, such as printing a message:
printf("CPU在偷懒了...
\r");Therefore, when an RTOS has no ready tasks, the CPU executes the system’s idle task, which by default performs no meaningful work unless the programmer adds code to it.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
