liveBook · Manning

Context switching

As explained in Software Design for Python Programmers

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

Context switching alternates execution among threads. On a single CPU, rapid switching enables concurrency; across multiple cores, threads can also execute in parallel. section 16.1

Dinner-party analogy

One person switching among cleaning, cooking, and setting the table models concurrency. Friends handling separate tasks model parallelism, while shared utensils require synchronization and mutual exclusion. section 16.1

Switching threads is not free. Mutexes, semaphores, condition objects, and context-switching costs can overwhelm the benefit of adding threads, while timing can make behavior difficult to reproduce and debug. section 16.5

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.
A diagram of a graph

AI-generated content may be incorrect.

Use the figure to inspect how threads share code, data, and external resources while retaining separate runtime stacks and apparent machine registers. section 16.1

How Software Design for Python Programmers covers it

How deep it goes
Explains switching, resource sharing, and performance costs, but stops short of detailed operating-system implementation steps.
Examples
Uses a dinner-party analogy and a three-thread application sharing memory, files, printers, stacks, and registers.
What you can do after
Evaluate multithreaded performance by weighing context-switching overhead against the benefits of additional threads.
How it connects
Connects context switching with multithreading, concurrency, parallelism, synchronization, mutual exclusion, 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 Software Design for Python Programmers. The section links point to the parts of the book it draws on.