liveBook · Manning

Preemption

As explained in 100 Go Mistakes and How to Avoid Them

Preemptive scheduling is a scheduling model in which the scheduler can interrupt an executing task and replace it with another task.

A common mistake is assuming that a goroutine yields only when it blocks. Since Go 1.14, a goroutine running for about 10 ms can be marked preemptible and context-switched, allowing a long-running job to share CPU time. section 8.2.1

Distinguish preemption from cooperative scheduling:

  • Before Go 1.14, context switches occurred only in specific blocking cases such as channel operations, I/O, or mutex acquisition. section 8.2.1
  • Since Go 1.14, the scheduler can interrupt a running goroutine and replace it with another runnable goroutine. section 8.2.1
  • The scheduler also balances runnable work through local queues, the global queue, and work stealing. section 8.2.1

A long-running goroutine

A CPU-intensive merge-sort goroutine need not reach a channel operation or other blocking point before another goroutine receives CPU time; after roughly 10 ms, it can be preempted. section 8.2.1

Figure 8.6 An example of the current state of a Go application executed on a four-core machine. Goroutines that aren’t in an executing state are either runnable (pending being executed) or waiting (pending a blocking operation).

Use the runtime-state figure to distinguish executing, runnable, and waiting goroutines across multiple processor cores. section 8.2.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines preemption, contrasts it with cooperative scheduling, and gives an approximate 10 ms threshold without detailing runtime internals.
Examples
Uses long-running work, parallel merge sort, runnable queues, and a four-core goroutine-state diagram.
What it assumes
Assumes familiarity with goroutines, blocking operations, and basic scheduler terminology.
What you can do after
Evaluate whether CPU-bound goroutines can share execution without explicit blocking operations.
How it connects
Connects preemption with goroutines, context switching, blocking operations, runnable queues, and work stealing.

Also explained in

Compare how 5 books explain preemption →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.