Multithreading runs multiple independently schedulable paths through a program. Threads may execute concurrently through rapid context switching or in parallel on different CPU cores, and any thread can spawn child threads. section 16.0 section 16.1
Shared code, data, files, and other resources require deliberate coordination. Mutexes enforce mutual exclusion, while condition variables synchronize execution more finely. section 16.0 section 16.1
Designing multithreaded programs typically involves:
- Protecting shared resources so only an allowed thread modifies them at a time. section 16.0
- Synchronizing related operations through mutexes and condition variables. section 16.0
- Balancing potential performance gains against synchronization, context-switching, and complexity costs. section 16.4
A race during singleton creation
If several threads call a singleton accessor while the object does not exist, each can observe a null pointer and create an object. The last assignment wins, so the program no longer has one reliable singleton. Thread-safe design must prevent this race. section 14.1.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.
Shows multiple threads sharing application code, data, files, and other resources while retaining separate runtime stacks. section 16.1










