liveBook · Manning

Synchronization

As explained in C++ Concurrency in Action, Second Edition

Synchronization is the coordination of operations across threads so their effects are correctly ordered or observed.

Synchronization coordinates operations across threads when one thread must wait for an event, a condition, or another thread’s task to finish. It avoids repeatedly checking shared flags and supports ordering or observing effects across threads. section 4.0

C++ offers several coordination facilities and broader ways to structure communication between tasks:

  • Condition variables, futures, promises, packaged tasks, latches, and barriers help coordinate operations. section 4.5
  • Functional-style programming, message passing, and continuations provide ways to organize task dependencies and communication. section 4.5
std::for_each(std::execution::par,v.begin(),v.end(),
    [&](int& x){ x=++count; });


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":14},{\"line\":0,\"ch\":33}]]"}
!@%STYLE%@!

This parallel for_each example updates a shared count, causing a data race and undefined behavior. Making count atomic or protecting it with a mutex restores defined behavior, but may serialize calls and undermine parallelism. section 10.2.3

Parallel-unsequenced algorithms impose a different constraint: their operations must not use synchronization or modify state shared between threads or elements. section 10.2.4

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Surveys coordination facilities and approaches, then works through a parallel-algorithm race and atomic or mutex alternatives.
Examples
Uses parallel for_each calls to contrast independent element updates with a shared counter race.
What you can do after
Diagnose shared-state races in parallel algorithms and restore defined behavior with an atomic or mutex, while recognizing possible serialization.
How it connects
Links synchronization to condition variables, futures, promises, packaged tasks, latches, barriers, mutexes, atomics, and message passing.

Also explained in

Compare how 11 books explain synchronization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.