8 Solving concurrency problems: Race conditions and synchronization

 

In this chapter:

  • You learn how to identify and solve one of the most common concurrency problems: race conditions
  • You learn how to share resources between tasks safely and reliably using synchronization primitives

In sequential programs, code execution follows a happy path of predictability and determinism; looking at it and understanding what it does is as easy as understanding how each function works, given the current state of the program. But in a concurrent program, the state of the program changes during execution. External circumstances, such as the OS scheduler, cache coherency, or platform compilers, can affect the order of execution and resources the program accesses. In addition, concurrent tasks conflict with each other when they compete for the same resources, such as CPU, shared variables, or files, which often cannot be controlled by the OS. This can all affect the result of the program.

Shared resources

Race conditions

Synchronization

Mutual exclusion

Semaphores

Atomic operations

Recap