liveBook · Manning

Race condition

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

A race condition is a concurrency defect in which program behavior depends on the timing or ordering of simultaneous operations.

A race condition occurs when simultaneous operations access shared data or resources and the result depends on which operation finishes first. The defect makes behavior unpredictable and difficult to debug. section 16.1

A singleton creation race

Suppose several threads call ExecutivePass::obtain() while the singleton does not yet exist. Each thread may observe single_instance as nullptr and create an object; the pointer then refers to whichever object was created last. The intended single object has become multiple objects because creation was not synchronized. 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.

Use the shared-resource diagram to trace how threads access memory, files, printers, and other resources concurrently. section 16.1

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

How deep it goes
Defines the defect and demonstrates singleton creation, while deferring specific avoidance techniques to multithreaded-program design.
Examples
Uses simultaneous singleton initialization and concurrent updates to a shared variable as concrete failure cases.
What you can do after
Diagnose timing-dependent behavior by identifying unsynchronized access to shared data or resources.
How it connects
Links multithreading, shared resources, synchronization, and the Singleton design pattern.

Also explained in

Compare how 20 books explain race condition →

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.