Preemption · operating systems

On this page 7

Preemption in operating systems is the act of forcibly suspending a running task so that the scheduler can give the processor to another task, without waiting for the current one to yield voluntarily. In processes & scheduling, it is the mechanism that lets a kernel enforce time limits and priorities, keep interactive programs responsive and stop a single misbehaving process from monopolizing the CPU.

The interrupted task is not terminated. Its execution context is saved in kernel data structures such as the process control block, and it returns to the run queue to resume later exactly where it stopped. Preemption is therefore a scheduling decision, not an error or a kill signal.

How preemption interrupts a running task

Preemption works because the kernel regains control through hardware interrupts that the running task cannot block from user mode. The most important source is the periodic timer interrupt, which fires at a configured rate and lets the scheduler check whether the current task has used up its time slice.

When the scheduler decides that another task should run, it sets a reschedule flag and performs a context switch at the next safe point. The switch saves registers, the program counter and the stack pointer, updates the task state from running to ready, and loads the saved context of the chosen task.

The following table lists the typical events that can trigger preemption and what each one means for the interrupted task.

TriggerWhat happensTypical effect
Time slice expiryTimer interrupt shows the quantum is used upTask moves to the back of its run queue
Higher-priority wakeupA blocked task with higher priority becomes readyCurrent task is suspended immediately or at the next safe point
I/O completionDevice interrupt wakes a waiting processInteractive or I/O-bound task may preempt a CPU-bound one
Inter-processor interruptAnother core asks this core to rescheduleLoad balancing or urgent wakeup on a multicore system
Priority changeA task priority is raised or lowered at runtimeScheduler reevaluates which task should run
Common triggers of preemption

Modern kernels such as Linux increasingly use tickless operation, where the timer is programmed for the next needed event instead of firing at a fixed rate. Preemption still happens, but the kernel avoids waking an idle core only to find that nothing needs to change.

User preemption and kernel preemption

Operating systems distinguish between preempting code that runs in user mode and preempting code that runs inside the kernel. Almost every general-purpose system preempts user-mode code, but kernel preemption is a separate design choice with its own costs.

With user preemption only, a task executing a system call keeps the CPU until it returns to user mode or blocks voluntarily. A fully preemptible kernel allows the switch almost anywhere in kernel code, except inside regions protected by spinlocks or with interrupts disabled, which lowers worst-case latency.

The table below compares the main preemption models that kernels offer.

ModelWhere preemption occursLatency profileTypical use
No forced preemptionOnly on return to user mode or when blockingHighest worst-case latencyThroughput-oriented servers
Voluntary preemptionAt explicit preemption points in kernel codeModerate latencyGeneral servers and desktops
Preemptible kernelAnywhere outside locked or atomic regionsLow latencyDesktops and responsive systems
Real-time preemptionNearly everywhere, with sleeping locks and threaded interruptsLowest and most predictable latencyIndustrial control and audio
Kernel preemption models

Linux exposes these models as build or boot options, and the PREEMPT_RT work, now merged into the mainline kernel, provides the real-time variant. Windows has used a preemptive kernel design since Windows NT, with interrupt request levels deciding when a dispatch can occur.

Preemption is the underlying mechanism, while preemptive multitasking is the scheduling policy built on top of it. Cooperative multitasking is the alternative in which a task gives up the CPU only when it yields, blocks or finishes, so one faulty loop can freeze the whole system.

Several scheduling algorithms exist in both a preemptive and a non-preemptive form, and the difference changes their behavior considerably.

AlgorithmNon-preemptive formPreemptive form
Shortest job firstShortest job runs to completion once startedShortest remaining time first replaces a longer job when a shorter one arrives
Priority schedulingNew high-priority task waits for the current oneNew high-priority task takes the CPU immediately
Round-robin schedulingNot meaningful without a time limitEach task runs for one time slice, then yields its place
First-come, first-servedNatural form of the algorithmRarely used, because order alone does not justify a switch
Earliest deadline firstDeadline checked only at task boundariesTask with the nearest deadline always runs
Scheduling algorithms with and without preemption

Aging, priority inheritance and multilevel feedback queues all rely on preemption. They adjust which task deserves the CPU, and preemption is what turns that decision into an actual switch.

Costs and tuning of preemption

Every preemption has a direct and an indirect cost. The direct cost is the context switch itself, usually in the range of a few microseconds on current hardware, depending on the processor, the address-space change and security mitigations.

The indirect cost is often larger: the incoming task finds cold caches and TLB entries, so it runs slowly until its working data is reloaded. Frequent preemption improves responsiveness but reduces throughput, which is the central trade-off of the mechanism.

The decision table below shows how administrators and developers usually balance this trade-off.

WorkloadRecommended approachReason
Batch computationLonger time slices, less kernel preemptionFewer switches preserve cache locality
Interactive desktopPreemptible kernel, short effective slicesInput and display stay responsive
Low-latency audioReal-time preemption and high thread priorityBuffers must be refilled within milliseconds
Hard real-time controlReal-time kernel with bounded latency analysisMissed deadlines can cause physical failures
Choosing a preemption strategy

Pitfalls and common misconceptions

Preemption introduces concurrency hazards even on a single core, because a task can be suspended between any two instructions. Code that reads and updates shared data must use locks, atomic operations or other synchronization primitives.

  • Priority inversion occurs when a high-priority task waits for a lock held by a low-priority task that is itself preempted; priority inheritance is the standard remedy.
  • Disabling preemption for long periods in kernel code destroys latency guarantees and is a frequent cause of audio dropouts.
  • Preemption does not guarantee fairness by itself; fairness depends on the scheduling policy that chooses the next task.
  • A preempted task is not slowed permanently; it simply waits in the ready state until the scheduler selects it again.

Understanding it simply

Think of a shared meeting room with a strict booking system. Each team may use the room for a fixed time, and when the time is up, the building manager asks the team to step out, even if they are mid-sentence. The team leaves its notes on the table exactly as they were and comes back later to continue.

In a computer, the operating system is that manager and the processor is the room. Preemption is the right to interrupt a running program, save its place and let another program work. This is why your music keeps playing smoothly while a large file is compressing in the background.

Applied in practice

A sound engineer records a live session on a Linux workstation with an audio buffer of 128 samples at 48 kHz, which leaves the audio thread less than three milliseconds to deliver each block. During the session, a background backup job starts reading thousands of files and keeps the kernel busy in long file-system calls.

On a kernel configured with voluntary preemption only, the audio thread occasionally waits too long, and the recording contains audible clicks. The engineer switches to a kernel with real-time preemption enabled and gives the audio thread a high real-time priority. The scheduler now preempts the backup task, including most of its kernel work, as soon as the audio thread wakes. The result is a recording without dropouts, while the backup still completes, only a few minutes later than before.