1. Why Do We Need CPU Scheduling?
The CPU is the core hardware in a computer responsible for executing instructions, but in modern operating systems, the programs running are usually far more numerous than the number of CPU cores.
For example, a computer may be running the following at the same time:
- Browser: handles web page rendering and JavaScript.
- IDE: performs code analysis and syntax checking.
- Database: handles query requests.
- Music player: continuously decodes audio.
- Background services: execute scheduled tasks and network requests.
If there is only one CPU core, these tasks cannot truly execute in parallel at the same moment.
The operating system needs to decide:
- Which task gets to use the CPU first?
- How long should the current task run?
- When should the current task be paused?
- Which task should run next?
- How can important tasks be guaranteed to get a chance to execute in time?
This is the problem that CPU scheduling solves.
1.1 Core Objectives of CPU Scheduling
CPU scheduling is not simply executing tasks in the order they arrive; rather, it balances multiple objectives.
| Scheduling Objective | Meaning | Optimization Direction |
|---|---|---|
| CPU utilization | The proportion of time the CPU is executing | Minimize idle time |
| Throughput | The number of tasks completed per unit time | Improve completion efficiency |
| Turnaround time | The total time from task submission to completion | Shorten as much as possible |
| Waiting time | The cumulative time a task waits in the ready queue | Minimize |
| Response time | The time from task submission to the first response | Shorten as much as possible |
| Fairness | How reasonably different tasks obtain CPU time | Avoid starvation |
| Real-time capability | Whether a task can complete before its deadline | Satisfy timing constraints |
These objectives are not always aligned.
For example:
- Prioritizing short tasks can reduce average waiting time.
- Prioritizing interactive tasks can improve user experience.
- Prioritizing high-priority tasks can ensure critical tasks execute in time.
- Giving each task the same amount of time can improve fairness.
Therefore, the operating system needs to choose scheduling policies based on the operating scenario.
1.2 Basic Idea of CPU Scheduling
The core of CPU scheduling is enabling multiple tasks to share limited processor resources.
On a single-core CPU, only the instructions of one thread can be executed at any given instant, but the operating system can rapidly switch between threads to make multiple tasks appear to run simultaneously.
flowchart TD
A["Multiple processes and threads"] --> B["Enter ready queue"]
B --> C["CPU scheduler selects a task"]
C --> D["Allocate CPU for execution"]
D --> E{"Continue running?"}
E -->|"Continue"| D
E -->|"Time slice exhausted"| F["Task re-enters ready queue"]
E -->|"Wait for I/O"| G["Enter blocked state"]
E -->|"Execution complete"| H["Task exits"]
F --> C
G --> I["I/O complete"]
I --> B
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style D fill:#FFF2CC,stroke:#E4C66A,color:#725719
style E fill:#F3EAF7,stroke:#BFA8CE,color:#59466B
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#F1F5F9,stroke:#CBD5E1,color:#475569
style H fill:#F1F5F9,stroke:#CBD5E1,color:#475569
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
2. Processes and Threads: The Basic Objects of CPU Scheduling
To understand CPU scheduling, you first need to understand what the operating system is actually scheduling.
In modern operating systems, the entities that actually participate in CPU execution scheduling are usually threads, not entire processes in the traditional sense.
2.1 What Is a Process?
A process is an instance of a running program and an important unit for resource management in the operating system.
A process typically has:
- An independent virtual address space.
- Code segment and data segment.
- Heap and memory-mapped regions.
- Open file descriptors.
- Signal handling configuration.
- One or more threads.
For example, a browser process may have multiple threads, responsible for interface handling, network requests, script execution, and background tasks respectively.
2.2 What Is a Thread?
A thread is the basic execution flow that the operating system can schedule and execute independently.
Each thread has its own execution context, including:
- Program counter (PC).
- CPU register state.
- Thread stack.
- Thread-local storage.
- Scheduling state and priority.
Multiple threads in the same process share process resources, such as:
- Code segment.
- Global data.
- Heap memory.
- File descriptors.
- Address space.
But they each have their own independent execution state.
2.3 Why Is Scheduling Usually Based on Threads?
Suppose a process contains three threads:
- T1: handles the user interface.
- T2: performs network requests.
- T3: performs background data computation.
If the operating system schedules only the entire process, then while T2 is waiting for network data, the whole process may be unable to continue executing.
With thread-level scheduling:
- T2 can enter the blocked state.
- T1 can continue handling user input.
- T3 can continue performing computation.
This can improve CPU utilization and program responsiveness.
2.4 Processes, Threads, and Scheduling Entities
Internal implementations differ across operating systems.
In Linux, the kernel uses the unified task structure task_struct to manage schedulable tasks. Whether it is a process or a thread, the kernel can treat it as a task entity.
In Linux:
- Each thread has its own task descriptor structure.
- Threads in the same thread group share some resources.
- The scheduler selects what to run at the granularity of runnable tasks.
Therefore, when discussing Linux CPU scheduling, terms such as task, task_struct, and runnable task are often used.
3. Lifecycle of Processes and Threads
CPU scheduling needs to know the current state of a task; only tasks that meet the conditions can be selected for execution.
3.1 Five Common Task States
| State | Meaning | Can It Be Scheduled? |
|---|---|---|
| New | Being created | No |
| Ready | Ready, waiting for CPU | Yes |
| Running | Executing on the CPU | Already running |
| Blocked | Waiting for I/O or another event | No |
| Terminated | Execution has finished | No |
Note that the task states actually used by the Linux kernel are more diverse; they cannot simply be equated with the five-state model above.
3.2 How Do States Transition?
flowchart TD
A["New (Creating)"] --> B["Ready"]
B --> C["Running"]
C -->|"Time slice exhausted or preempted"| B
C -->|"Waiting for I/O or an event"| D["Blocked"]
D -->|"Waiting condition satisfied"| B
C -->|"Execution finished"| E["Terminated"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#FFF2CC,stroke:#E4C66A,color:#725719
style D fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style E fill:#F1F5F9,stroke:#CBD5E1,color:#475569
Among them, the three most important states are:
- Ready: The task is ready to execute but has not yet been allocated the CPU.
- Running: The task is currently executing on the CPU.
- Blocked: The task cannot continue for now because it is waiting for some resource or event.
The scheduler mainly selects the next task to run from among ready tasks.
3.3 What Is the Ready Queue?
The ready queue holds tasks that currently meet execution conditions and are waiting for the CPU.
For example:
Ready Queue
T1
T2
T3
T4
T5
The scheduler selects tasks according to the scheduling policy.
Different scheduling algorithms may use different data structures:
- FIFO queue.
- Priority queue.
- Multilevel feedback queue.
- Balanced search tree.
- Per-CPU run queue.
In Linux, the traditional CFS scheduling class uses a red-black tree to manage runnable entities; the modern EEVDF scheduling mechanism selects tasks based on virtual deadlines and virtual runtimes.
Therefore, one cannot simply assume that all operating systems use a single ordinary FIFO queue to manage all tasks.
4. Levels of CPU Scheduling
Scheduling in an operating system is not a single step but involves different levels.
4.1 Long-Term Scheduling
Long-term scheduling, also called job scheduling, mainly determines which jobs can enter the system for execution.
It usually focuses on:
- How many jobs the system admits at the same time.
- The ratio of CPU-intensive to I/O-intensive jobs.
- Whether system resources are sufficient.
Long-term scheduling is more important in traditional batch processing systems; in modern general-purpose operating systems, its role and implementation differ.
4.2 Medium-Term Scheduling
Medium-term scheduling is mainly responsible for adjusting the residency status of tasks in the system.
For example, when system memory is insufficient, some processes can be swapped out and later swapped back in according to conditions.
It mainly addresses:
- Memory pressure.
- The number of resident processes.
- Balancing resource usage.
Modern operating systems usually manage memory pressure through mechanisms such as virtual memory, page reclaim, and memory compression, and do not necessarily use the traditional model of swapping out entire processes.
4.3 Short-Term Scheduling
Short-term scheduling, also called CPU scheduling, is the most direct processor allocation mechanism.
It determines:
- Which ready thread gets the CPU.
- When task switching occurs.
- Whether the current task needs to be preempted.
Short-term scheduling runs very frequently, so scheduling overhead must be minimized as much as possible.
4.4 Relationship Among the Three Scheduling Levels
flowchart TD
A["Job submission"] --> B["Long-term scheduling"]
B --> C["Enter the system run queue"]
C --> D["Medium-term scheduling"]
D --> E["Resident in memory and ready to run"]
E --> F["Short-term scheduling"]
F --> G["Allocate CPU for execution"]
G --> H{"Task state"}
H -->|"Continue execution"| G
H -->|"Wait for resources"| I["Blocked or suspended"]
H -->|"Execution complete"| J["Task finished"]
I --> D
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#FFF2CC,stroke:#E4C66A,color:#725719
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#F3EAF7,stroke:#BFA8CE,color:#59466B
style I fill:#F1F5F9,stroke:#CBD5E1,color:#475569
style J fill:#F1F5F9,stroke:#CBD5E1,color:#475569
V. CPU Scheduling Algorithms
Different scheduling algorithms have different task selection rules.
Common algorithms include:
- First-Come, First-Served (FCFS).
- Shortest Job First (SJF).
- Shortest Remaining Time First (SRTF).
- Round Robin (RR).
- Priority scheduling.
- Multilevel queue scheduling.
- Multilevel feedback queue scheduling.
5.1 First-Come, First-Served (FCFS)
First Come First Served, meaning first-come, first-served.
Basic rules:
- Whichever task enters the ready queue first gets the CPU first.
- While a task is running, it is usually not preempted by other ordinary tasks.
- After the current task completes or blocks, the next task is executed.
For example:
| Task | Arrival Time | CPU Execution Time |
|---|---|---|
| P1 | 0 | 8 |
| P2 | 1 | 4 |
| P3 | 2 | 2 |
Execution order:
flowchart LR
A["P1 runs 8"] --> B["P2 runs 4"]
B --> C["P3 runs 2"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B5A4DC,color:#514276
Gantt chart:
Timeline:
0 8 12 14
|--- P1 ---|-- P2 --| P3 |
Advantages:
- Simple to implement.
- Low scheduling overhead.
- The execution order is easy to understand.
Disadvantages:
- Short tasks may wait for a long time.
- Prone to the Convoy Effect.
- Not suitable for interactive systems.
The Convoy Effect refers to a long-running task at the head of the queue forcing many short tasks to wait.
5.2 Shortest Job First (SJF)
Shortest Job First, meaning the shortest job is prioritized.
Basic rules:
- Prefer the task with the shortest estimated CPU execution time.
- It can significantly reduce the average waiting time.
- Classic SJF is usually non-preemptive.
For example:
| Task | CPU execution time |
|---|---|
| P1 | 8 |
| P2 | 4 |
| P3 | 2 |
If the three tasks arrive at the same time, the execution order is:
flowchart LR
A["P3 runs 2"] --> B["P2 runs 4"]
B --> C["P1 runs 8"]
style A fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
Advantages:
- Theoretically minimizes the average waiting time.
- Suitable for batch processing scenarios where execution times can be predicted accurately.
Disadvantages:
- Actual run times usually cannot be known accurately in advance.
- Long tasks may be denied execution opportunities for a long time.
- Not suitable for direct use in general-purpose interactive scheduling.
5.3 Shortest Remaining Time First (SRTF)
Shortest Remaining Time First is the preemptive version of SJF.
Basic rules:
- Select the task with the shortest remaining execution time.
- If a new task arrives and its remaining time is shorter than that of the current task, it can preempt the current task.
For example:
| Task | Arrival time | Execution time |
|---|---|---|
| P1 | 0 | 8 |
| P2 | 1 | 4 |
| P3 | 2 | 2 |
Execution process:
flowchart TD
A["P1 starts at time 0"] --> B["At time 1, P2 arrives"]
B --> C["P2 has a shorter remaining time and preempts P1"]
C --> D["At time 2, P3 arrives"]
D --> E["P3 has the shortest remaining time and preempts P2"]
E --> F["P3 completes"]
F --> G["P2 resumes and completes"]
G --> H["P1 resumes and completes"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style F fill:#FFF2CC,stroke:#E4C66A,color:#725719
style G fill:#FFF2CC,stroke:#E4C66A,color:#725719
style H fill:#FFF2CC,stroke:#E4C66A,color:#725719
The corresponding execution timeline:
0 1 2 4 7 14
| P1 | P2 | P3 | P2 | P1 |
Advantages:
- Can reduce the average waiting time.
- Newly arrived short tasks can quickly get a chance to execute.
Disadvantages:
- Requires estimating the remaining execution time of tasks.
- The number of preemptions may be high.
- Long tasks may starve.
5.4 Round Robin (RR)
Round Robin, also known as time-slice rotation.
This is a typical preemptive scheduling algorithm, often used as a time-sharing system model in teaching.
Basic rules:
- All ready tasks enter a circular queue.
- The scheduler selects tasks in queue order.
- Each task runs for at most one time slice.
- When the time slice is exhausted, if the task is still unfinished, it re-enters the tail of the queue.
- Repeat until tasks complete or block.
Assume a time slice of 2:
| Task | Execution time |
|---|---|
| P1 | 5 |
| P2 | 4 |
| P3 | 3 |
Execution process:
flowchart TD
A["Ready queue P1 P2 P3"] --> B["P1 runs for 2"]
B --> C["P2 runs for 2"]
C --> D["P3 runs for 2"]
D --> E["P1 has 3 left, back to the tail"]
E --> F["P2 has 2 left, back to the tail"]
F --> G["P3 has 1 left, back to the tail"]
G --> H["Keep rotating until all tasks finish"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style D fill:#FFF2CC,stroke:#E4C66A,color:#725719
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style G fill:#FFF2CC,stroke:#E4C66A,color:#725719
style H fill:#F1F5F9,stroke:#CBD5E1,color:#475569
Gantt chart:
Timeline:
0 2 4 6 8 10 11 12
|P1 |P2 |P3 |P1 |P2 |P3 |P1 |
Advantages:
- Relatively fair.
- Every ready task gets the CPU periodically.
- Suited to interactive scenarios.
Disadvantages:
- Too short a time slice causes a large number of context switches.
- Too long a time slice reduces interactive responsiveness.
- Limited ability to distinguish between different types of tasks.
Time slice size is the key parameter of the RR algorithm.
Time slice too short:
- Frequent context switches.
- CPU time is consumed by scheduling overhead.
Time slice too long:
- Response time gets worse.
- The algorithm gradually approaches FCFS.
5.5 Priority Scheduling
Priority Scheduling decides the execution order based on task priority.
For example:
| Task | Priority |
|---|---|
| P1 | 3 |
| P2 | 1 |
| P3 | 2 |
Assuming the smaller the number, the higher the priority:
flowchart TD
A["Multiple ready tasks"] --> B["Compare task priorities"]
B --> C["Select the highest-priority task"]
C --> D["Gets the CPU and runs"]
D --> E{"Is there a higher-priority task?"}
E -->|"Yes"| F["Preempt the current task"]
E -->|"No"| G["Continue running"]
F --> B
G --> H["Task completes or blocks"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style D fill:#FFF2CC,stroke:#E4C66A,color:#725719
style E fill:#F3EAF7,stroke:#BFA8CE,color:#59466B
style F fill:#FCE8E6,stroke:#E2A5A0,color:#783F3B
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#F1F5F9,stroke:#CBD5E1,color:#475569
Advantages:
- Ensures that important tasks are executed first.
- Suited to real-time systems and critical task management.
Disadvantages:
- Low-priority tasks may wait for a long time.
- Priority inversion may occur.
A common technique for solving the starvation problem is Aging, that is, priority aging.
As a task's waiting time increases, the system gradually raises its effective priority, so that tasks that have waited a long time can eventually obtain the CPU.
5.6 Multilevel Queue Scheduling
Multilevel Queue Scheduling divides tasks into different ready queues.
For example:
- System task queue.
- Interactive task queue.
- Batch task queue.
- Background task queue.
Each queue can use a different scheduling algorithm.
flowchart TD
A["All ready tasks"] --> B["Multilevel queue scheduler"]
B --> C["System task queue"]
B --> D["Interactive task queue"]
B --> E["Batch task queue"]
B --> F["Background task queue"]
C --> G["High-priority execution"]
D --> H["Round-robin time slicing"]
E --> I["Batch scheduling"]
F --> J["Low-priority execution"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style C fill:#FCE8E6,stroke:#E2A5A0,color:#783F3B
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#FFF2CC,stroke:#E4C66A,color:#725719
style F fill:#F1F5F9,stroke:#CBD5E1,color:#475569
style G fill:#FCE8E6,stroke:#E2A5A0,color:#783F3B
style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style I fill:#FFF2CC,stroke:#E4C66A,color:#725719
style J fill:#F1F5F9,stroke:#CBD5E1,color:#475569
Advantages:
- Can distinguish between different types of tasks.
- Each queue can adopt a different strategy.
- Convenient for managing tasks with different priorities.
Disadvantages:
- Priority relationships between queues may cause starvation.
- Tasks are usually fixed to a certain queue, resulting in insufficient flexibility.
5.7 Multilevel Feedback Queue MLFQ
Multilevel Feedback Queue is a scheduling algorithm that can dynamically adjust queues based on task execution behavior.
It not only selects the execution target based on task priority, but also adjusts its queue position according to how the task uses the CPU.
Basic idea:
- New tasks enter the high-priority queue.
- Tasks that frequently voluntarily yield the CPU may maintain a higher priority.
- Tasks that occupy the CPU for a long time gradually move to lower-priority queues.
- Tasks that wait for a long time can gain execution opportunities through priority boosting.
For example:
flowchart TD
A["New task arrives"] --> B["High-priority queue Q0"]
B --> C["Allocate a shorter time slice"]
C --> D{"Is the task completed?"}
D -->|"Completed"| E["Task exits"]
D -->|"Not completed"| F["Enter medium-priority queue Q1"]
F --> G["Allocate a longer time slice"]
G --> H{"Is the task completed?"}
H -->|"Completed"| E
H -->|"Not completed"| I["Enter low-priority queue Q2"]
I --> J["Wait for CPU execution"]
J --> K["Periodic priority boost"]
K --> B
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style D fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style E fill:#FFF2CC,stroke:#E4C66A,color:#725719
style F fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style I fill:#F1F5F9,stroke:#CBD5E1,color:#475569
style J fill:#F1F5F9,stroke:#CBD5E1,color:#475569
style K fill:#FFF2CC,stroke:#E4C66A,color:#725719
Advantages:
- Can accommodate both interactive tasks and CPU-intensive tasks.
- Dynamically adjusts scheduling priority based on runtime behavior.
- More flexible than fixed-priority scheduling.
Disadvantages:
- Implementation and parameter configuration are relatively complex.
- The number of queues, time slices, and priority boost period need to be set reasonably.
6. Preemptive and Non-preemptive Scheduling
CPU scheduling algorithms can also be classified according to whether they allow interruption of the currently running task.
6.1 Non-preemptive Scheduling
Non-preemptive Scheduling.
Once a task obtains the CPU, it usually continues running until:
- It finishes execution.
- It voluntarily enters a blocked state.
- It voluntarily yields the CPU.
Characteristics:
- Simple scheduling logic.
- Less context switching.
- Long tasks may affect the responsiveness of short tasks.
Typical algorithms:
- FCFS.
- Classic non-preemptive SJF.
6.2 Preemptive Scheduling
Preemptive Scheduling.
The operating system allows the currently running task to be suspended and the CPU to be allocated to another task.
Common preemption conditions:
- The time slice expires.
- A higher-priority task enters the ready state.
- The current task no longer meets the conditions for running.
- The scheduling policy decides to switch to another task.
Typical algorithms:
- RR.
- SRTF.
- Preemptive priority scheduling.
6.3 Comparison of the Two Scheduling Approaches
| Comparison dimension | Non-preemptive | Preemptive |
|---|---|---|
| Actively interrupts tasks | Usually no | Yes |
| Response speed | Relatively slow | Usually fast |
| Context switching | Less | Possibly more |
| Scheduling complexity | Lower | Higher |
| Interactive experience | Relatively weak | Usually better |
| Typical scenarios | Simple batch processing | General-purpose interactive systems |
Preemptive scheduling does not mean that a task can be switched unconditionally between arbitrary machine instructions. An actual switch must satisfy the constraints of the processor, interrupts, and the kernel scheduling mechanism.
7. Time Slices and Context Switching
CPU scheduling not only determines the order in which tasks execute but also needs to handle saving and restoring state when tasks are switched.
7.1 What Is a Time Slice?
A time slice is a period of CPU execution time allocated to a task by the scheduler.
For example:
Time slice = 10 ms
T1: runs 10 ms
T2: runs 10 ms
T3: runs 10 ms
T1: runs again 10 ms
The purpose of a time slice is to limit the amount of time a single task can continuously occupy the CPU.
However, note the following:
- A time slice is not a fixed, uniform parameter used by all operating systems.
- Different scheduling policies may use different time allocation methods.
- Linux's actual scheduling mechanism is not equivalent to fixed time-slice round-robin.
7.2 What Is a Context Switch?
A context switch is the process by which the operating system suspends the current task and restores the execution state of another task.
When the CPU executes a thread, the current thread's execution state is stored in its internal registers.
If it needs to switch to another thread, it must save the current thread's state and restore the target thread's state.
A typical context includes:
- General-purpose registers.
- Program counter.
- Stack pointer.
- Flag register.
- Other architecture-related processor state.
7.3 Context Switch Process
flowchart TD
A["Thread T1 is running"] --> B["A timer interrupt or other scheduling event occurs"]
B --> C["Enter the kernel"]
C --> D["Save the execution context of T1"]
D --> E["Update the task state of T1"]
E --> F["The scheduler selects T2"]
F --> G["Restore the execution context of T2"]
G --> H["Switch to T2 for execution"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF2CC,stroke:#E4C66A,color:#725719
style C fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#E8E2F8,stroke:#B5A4DC,color:#514276
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
7.4 Why Does Context Switching Have Overhead?
A context switch itself requires additional kernel operations.
In addition, it may also cause:
- Reduced CPU cache locality.
- TLB cache invalidation or flushing.
- Branch prediction state being affected.
- Scheduling data structure maintenance overhead.
- Cache coherence communication between multiple cores.
However, one should not assume that every thread switch completely clears the CPU cache or TLB. Modern processors and operating systems use various mechanisms to reduce these overheads.
7.5 What Is the Difference Between Thread Switching and Process Switching?
Thread switching:
- Save the current thread's execution state.
- Restore the target thread's execution state.
- If the two threads belong to the same process, switching the address space is usually not required.
Process switching:
- May require switching the address space.
- May require updating page-table-related state.
- May affect TLB and cache locality.
Therefore, switching between threads in the same process is usually lighter than switching between different processes, but the specific cost depends on the operating system and hardware architecture.
8. How Does Linux Perform CPU Scheduling?
Linux is a very typical scheduling implementation among modern operating systems.
Understanding Linux scheduling mechanisms can help us connect the preceding theory with real systems.
8.1 Basic Structure of the Linux Scheduler
The Linux kernel organizes scheduling policies for different types of tasks through scheduling classes.
Common scheduling classes include:
| Scheduling class | Purpose | Typical policy |
|---|---|---|
| Stop | Special kernel scheduling tasks | Internal use |
| Deadline | Deadline scheduling | SCHED_DEADLINE |
| Real-time | Real-time tasks | SCHED_FIFO, SCHED_RR |
| Fair | Normal tasks | SCHED_NORMAL, etc. |
| Idle | Idle tasks | When the CPU has no other runnable tasks |
These scheduling classes have different priorities and selection rules.
Usually, the scheduler gives precedence to scheduling classes with higher scheduling priority.
Note: The scheduling mechanism for normal tasks varies across Linux kernel versions. The implementations of traditional CFS and modern EEVDF cannot be conflated.
8.2 Linux Normal Task Scheduling: CFS
CFS stands for Completely Fair Scheduler.
It has long been the core mechanism for normal task scheduling in Linux.
The basic idea of CFS is:
to give each task a relatively fair share of CPU time according to its weight.
CFS uses virtual runtime vruntime to measure the CPU resources a task has already received.
A simplified way to understand it is:
- The longer the actual runtime, the more the virtual runtime usually grows.
- The higher the weight, the slower the virtual runtime grows.
- The scheduler tends to choose tasks with smaller virtual runtime.
Simplified formula:
Where:
runtime: actual CPU execution time.weight: task weight.NICE_0_LOAD: standard weight baseline.
The higher the weight, the smaller the virtual runtime increment corresponding to the same actual runtime.
8.3 nice Values and Task Weights
Linux normal tasks can influence their scheduling weight through the nice value.
nice value range:
-20 to +19
Generally speaking:
- The lower the nice value, the higher the scheduling weight.
- The higher the nice value, the lower the scheduling weight.
For example:
nice -n 10 ./worker
Start the program with a lower priority.
nice -n -5 ./worker
Start the program with a higher priority, which usually requires appropriate permissions.
You can also use renice to change the nice value of a running process:
renice -n 5 -p 1234
View process priority:
ps -o pid,ni,pri,stat,comm -p 1234
Note the following:
- The nice value is not a real-time priority.
- The nice value mainly affects the weight in the normal scheduling class.
- The nice value does not guarantee that a task will get CPU at a particular point in time.
8.4 Modern Linux Normal Scheduling: EEVDF
Newer Linux kernels are gradually adopting the EEVDF scheduling mechanism.
The full name of EEVDF is Earliest Eligible Virtual Deadline First.
It combines two core concepts:
- Eligible: whether a task is eligible to participate in scheduling.
- Virtual Deadline: a task’s deadline on the virtual timeline.
The scheduler selects the task with the earliest virtual deadline from among the eligible tasks.
Its design goals are to improve fairness and better handle latency-sensitive tasks.
When understanding EEVDF, it is necessary to distinguish it from CFS's traditional virtual runtime model:
- The traditional CFS implementation mainly selects tasks based on the smallest virtual runtime.
- EEVDF introduces eligibility checks and virtual deadlines.
- EEVDF is not equivalent to simple sorting by real-world deadlines.
8.5 Linux Real-Time Scheduling
Linux also provides real-time scheduling policies.
SCHED_FIFO
First-in, first-out real-time scheduling.
Features:
- Tasks with the same priority execute in the order they enter the ready state.
- They do not automatically rotate because a normal time slice is exhausted.
- Tasks with higher real-time priority can preempt the current task.
- The current task can voluntarily yield the CPU or enter a blocked state.
SCHED_RR
Real-time round-robin scheduling.
Features:
- Tasks with the same real-time priority use time-slice round-robin scheduling.
- Higher-priority tasks can preempt lower-priority tasks.
- Tasks with the same priority get opportunities to execute in turn.
View scheduling policy:
chrt -p 1234
Run the program with a real-time policy:
sudo chrt -f 50 ./realtime_worker
The priority here and the nice value of ordinary tasks belong to different scheduling systems.
Real-time scheduling has a significant impact on the system, and improper configuration may prevent ordinary tasks from running for a long time.
8.6 Linux Multicore Scheduling
Modern CPUs usually have multiple cores.
For example:
CPU 0
CPU 1
CPU 2
CPU 3
Linux maintains a corresponding run queue and scheduling state for each CPU.
The scheduler needs to address:
- Which task should each CPU run?
- Do tasks need to be migrated to other CPUs?
- How should the load across CPUs be balanced?
- How can cache locality be preserved as much as possible?
- How should NUMA memory access costs be taken into account?
Multicore scheduling is not simply a matter of distributing all tasks evenly across every core.
For example: