liveBook · Manning

Context switching

As explained in Object-Oriented Software Design in C++

Context switching is the operating-system operation of saving one thread's execution state and restoring another's so execution can move between them.

Context switching rapidly moves a single CPU among multiple threads, creating the appearance of simultaneous execution. Modern multicore systems can also execute threads in parallel on different CPUs. section 16.1

Dinner-party analogy

Doing the cleaning, cooking, and table setting yourself while moving among tasks models concurrency. Having friends handle separate tasks models parallelism; coordinating shared pans and utensils illustrates mutual exclusion. section 16.1

Account for these consequences when designing multithreaded applications:

  • Protect shared resources and synchronize threads. section 16.1
  • Expect runtime scheduling to produce timing-dependent, irreproducible behavior. section 16.4
  • Balance additional threads against mutex, condition-variable, and context-switching costs. section 16.4
Figure 16.1 A multithreaded application with three threads. The threads share the application’s internal resources of code and data in memory and external resources such as printers and files. The runtime system gives each thread its own runtime stack and the appearance of having its own set of machine registers.

Visualizes threads sharing code, data, printers, and files while receiving separate runtime stacks and the appearance of separate machine registers. section 16.1

How Object-Oriented Software Design in C++ covers it

How deep it goes
Defines switching and contrasts concurrency with parallelism, then stops short of describing the saved execution state or switching mechanism.
Examples
Uses a dinner-party analogy and a three-thread resource-sharing figure to illustrate concurrency, parallelism, and thread-local runtime resources.
What you can do after
Evaluate multithreaded designs by weighing synchronization, scheduling unpredictability, deadlocks, and context-switching overhead.
How it connects
Connects context switching with multithreading, concurrency, parallelism, mutual exclusion, mutexes, condition variables, and deadlocks.

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 Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.