有一个特殊的“空闲”任务,PID=0,有时称为swapper (Why do we need a swapper task in linux?)。当没有其他任务准备好运行时,此任务被安排到 CPU 内核。有几个空闲任务 - 每个 CPU 内核一个
来源kernel/sched/core.chttp://lxr.free-electrons.com/source/kernel/sched/core.c?v=3.16#L3160
3160 /**
3161 * idle_task - return the idle task for a given cpu.
3162 * @cpu: the processor in question.
3163 *
3164 * Return: The idle task for the cpu @cpu.
3165 */
3166 struct task_struct *idle_task(int cpu)
3167 {
3168 return cpu_rq(cpu)->idle;
3169 }
3170
因此,指向该任务的指针存储在运行队列中(struct rq)kernel/sched/sched.h:
502 * This is the main, per-CPU runqueue data structure. ... */
508 struct rq {
557 struct task_struct *curr, *idle, *stop;
sched/core.c 中有一些初始化代码:
4517 /**
4518 * init_idle - set up an idle thread for a given CPU
4519 * @idle: task in question
4520 * @cpu: cpu the idle task belongs to
4524 */
4525 void init_idle(struct task_struct *idle, int cpu)
我认为,idle task 会运行某种带有特殊 asm 命令的循环,以通知 CPU 内核没有有用的工作......
这篇帖子http://duartes.org/gustavo/blog/post/what-does-an-idle-cpu-do/ 说空闲任务执行cpu_idle_loop kernel/sched/idle.c(可能有用于arch 和CPU 的自定义版本的循环 - 用cpu_idle_poll(void) 调用-> cpu_relax();):
40 #define cpu_relax() asm volatile("rep; nop")
45 static inline int cpu_idle_poll(void)
..
50 while (!tif_need_resched())
51 cpu_relax();
221 if (cpu_idle_force_poll || tick_check_broadcast_expired())
222 cpu_idle_poll();
223 else
224 cpuidle_idle_call();