On a real hardware only one task can run at once, hence why the need for a task scheduler. To do that, the concept of virtual runtime is introduced, which specifies when its next timeslice would start executing on the ideal multi-tasking CPU.

In Linux, the implementation is called CFS (Completely Fair Scheduler).

The task are picked based on p->se.vruntime, which is a per-task measure of the virtual runtime. It aims to always try to run the task with the smallest vruntime value.

To do that, it uses a time-ordered rbtree, where all runnable tasks are sorted by p->se.vruntime key and picking the task is essentially just picking the leftmost task (the one with lowest p->se.vruntime).

The implementation of the rbtree in Linux has an additional ready queue which caches a pointer to the leftmost node, making the operation O(1) instead of O(log n), making it par with the heap complexity. Another reason why rbtree is being chosen is that heaps are array based and hence require contiguous memory in kernel space, making it unsuitable for storing thousands of entities.

See also

References