Sections[conc]

Concurrency

Threads, atomics, locks, coroutines and asynchronous code in standard C++ and its libraries, for developers whose code runs on more than one thread.

Clause
5 of 8
Answers
2, newest first
Written for
C++20, C++23
Written by

Threads and a memory model arrived in C++11; std::jthread and coroutines followed in C++20, and std::generator in C++23. This section covers what the standard provides, what libraries such as Asio add, and the tools that find data races. Start with co_yield and std::generator, a lazy sequence whose body runs only when a loop pulls the next value, on the caller’s thread.

In this section

  • Threads, jthread and stop tokens
  • Mutexes, locks and condition variables
  • Atomics and the memory model
  • Coroutines
  • Generators and lazy sequences
  • Asynchronous I/O and Asio
  • Senders, receivers and executors
  • Parallel algorithms
  • Lock-free data structures
  • Data races and the sanitizers that find them
  • Thread pools and task systems

Answers in Concurrency 2, newest first

  1. C++ generators: co_yield and std::generator

    Write a lazy sequence with co_yield: std::generator in C++23, a complete C++20 generator for libraries without it, and the lifetime rules that stop dangling.

    §5.17 min readC++23

    written for C++23

  2. std::thread and std::jthread: start, join and stop a thread

    Start a thread with std::thread or std::jthread (C++20): pass arguments with std::ref, get a result, stop it with a stop_token, and what a missed join prints.

    §5.25 min readC++20

    written for C++20