liveBook · Manning

Preemption

As explained in Grokking Concurrency

Preemptive multitasking is an operating-system technique in which the system can suspend a running task without requiring its cooperation and schedule another task.

Imagine an arcade machine waiting for a player to press a button. Rather than leave the processor idle, it can give other work a turn. Preemptive multitasking lets the operating system suspend a running task without waiting for it to cooperate, then schedule another task. section 6.7 section 6.8

One approach gives each task a time slice: a period during which it can use the CPU. If the task has not blocked and its slice expires, the scheduler interrupts it and lets another task run. The suspended task waits for another turn. This time-sharing policy helps the system distribute processor time among tasks. section 6.7

Follow three tasks over time to see how interleaving can make them appear to run simultaneously. section 6.7

On a single core, fast switching creates the impression that tasks run at once, even though only one executes at a given moment. This is concurrency, not parallel execution. Switching has a cost: with too many tasks, the system can spend too much time on context switches instead of useful work. section 6.7 section 6.14

An arcade machine shares its processor

An arcade game can use time spent waiting for player input to compute the game world or render a screen. In a simple time-sharing model, a timer interrupts the current thread so another thread can use the processor. Fast switching makes the game feel responsive while several tasks make progress. section 6.8

A threaded server handles clients

A server can accept connections on a main thread and handle each client on a separate thread. The operating system schedules the threads, so the request-handling code does not need to manage low-level scheduling itself. section 10.6

Preemption contrasts with cooperative multitasking, where tasks must yield control themselves. Cooperative approaches can reduce management overhead for many I/O tasks, but they require tasks to decide when to let others run. section 12.12

How Grokking Concurrency covers it

How deep it goes
Explains time slices, interrupts, and interleaving, then illustrates scheduling with a timer-driven arcade model and a threaded server.
Examples
Illustrates preemption with an arcade machine and a server that assigns each client a thread.
What you can do after
Evaluate preemption as a way to share CPU time, recognizing switching overhead and the difference between concurrency and parallelism.
How it connects
Connects preemption with time sharing, concurrency, context switching, and cooperative multitasking.

Also explained in

Compare how 6 books explain preemption →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Concurrency. The section links point to the parts of the book it draws on.