liveBook · Manning

Context switching

As explained in 100 Go Mistakes and How to Avoid Them

Context switching is the act of suspending one execution context and resuming another on a processor or runtime worker.

Context switching suspends one execution context and resumes another. A CPU core switches between OS threads by saving execution state, while the Go runtime switches goroutines on and off OS threads. Goroutines use less memory than OS threads, making their switches faster. section 8.2.1

Avoid treating more goroutines as automatic parallelism:

  • For CPU-bound work, too many goroutines can make threads share execution time, increasing context switches. section 8.5
  • A worker pool near the number of available threads can reduce unnecessary switching when the workload is CPU-bound. section 8.5
  • I/O-bound pools depend mainly on the external system, so workload classification comes before choosing the pool size. section 8.5

Sizing a CPU-bound worker pool

Use runtime.GOMAXPROCS(0) to inspect the configured processor limit, then size a CPU-bound worker pool accordingly. A fixed pool can receive tasks through a shared channel, process them concurrently, and wait for completion; validate the choice with benchmarks rather than assuming it is optimal. section 8.5

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains saved thread state, goroutine-to-thread switching, scheduler states, and workload effects, but does not prescribe a universal pool size.
Examples
Uses four-core scheduling diagrams, a fixed worker pool, a shared channel, and a GOMAXPROCS query.
What it assumes
Assumes familiarity with goroutines, threads, CPU cores, channels, and worker pools while defining their scheduling relationship.
What you can do after
Build CPU-bound worker pools, reduce avoidable switching, and validate concurrency assumptions with benchmarks.
How it connects
Connects context switching with goroutines, OS threads, Go scheduler, GOMAXPROCS, worker pools, and CPU-bound or I/O-bound workloads.

Also explained in

Compare how 9 books explain context switching →

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.