Threads, mutexes and atomics

Running work in parallel, and the data race that silently loses updates when two threads share a counter.

What you'll learn
  • Start and join threads with std::thread and std::jthread
  • Protect shared state with a mutex and lock_guard
  • Explain a data race at the level of load, add and store, and fix it with std::atomic

Threads

std::thread t1(print_thread_id, 0);
t1.join();                                   // wait for it

std::vector<std::jthread> my_threads;
for (int i = 0; i < 3; i++)
    my_threads.emplace_back(print_thread_id, i);

33threads.cpp starts a std::thread and joins it, then starts std::jthreads (C++20), which join automatically in their destructor — RAII again. Forgetting to join a plain std::thread calls std::terminate. Note the emplace_back from lesson 8: the arguments are forwarded straight to the jthread constructor.

Several threads writing to std::cout at once may interleave their output. 34mutex.cpp serialises them with a mutex:

std::mutex m;
auto print_thread_id = [&m](int id) {
    std::lock_guard<std::mutex> lg(m);       // locks here, unlocks at the closing brace
    std::cout << "Printing from the thread: " << id << '\n';
};

A data race

35atomic.cpp has two threads each add 1 to a shared counter 100,000 times. With std::atomic<int> it prints 200,000, every time. The comment in the file explains why it is atomic: with a plain int, the program has a data race.

The reason is that counter += 1 on an int is three steps — load the value into a register, add one, store it back — and another thread can run between them:

Two threads, six increments each. With a plain int, a thread that loaded the counter before the other stored to it writes back a stale value, and an increment vanishes. With std::atomic, each increment is one indivisible step. Change the seed for a different interleaving.</figcaption> </figure> Replacing `std::atomic` with `int` and running it twelve times (built with `-O0`) gave six wrong answers, as low as 138,668:
Half the runs lose increments, by a different amount each time. Built with -O2 instead, the same program printed 200,000 in ten runs out of ten — the optimiser turns the loop into a single add, which shrinks the window but does not remove the race.
That last point is the dangerous one. A data race is undefined behaviour, not merely a wrong number, and a program can pass every test on one machine and compiler setting and fail on another. `-fsanitize=thread` detects it reliably. With `std::atomic`, `counter += 1` compiles to a single locked instruction (`lock add` on x86-64) that no other core can interrupt. A mutex would also fix it, at a higher cost per increment; for one shared counter, an atomic is the right tool, and for anything larger the best fix is not to share — give each thread its own partial sum and add them at the end. ## Parallel algorithms `32parallel_stl_algo.cpp` asks the standard library to parallelise a reduction: ```cpp std::vector my_vector(1 << 30); // 2^30 ints = 4 GiB auto r = std::reduce(std::execution::par_unseq, my_vector.begin(), my_vector.end(), 0); ``` With libstdc++ the parallel policies are implemented on top of Intel TBB. Without `<tbb/tbb.h>` installed, the header silently selects its serial backend: the program compiles and runs, but on one core. Install `libtbb-dev` and link with `-ltbb` to get real parallelism. (The vector also needs 4 GiB of free memory.)

Try it yourself. Replace std::atomic<int> with int in 35atomic.cpp, build with -O0 -g -fsanitize=thread, and read the report. (On recent Linux kernels ThreadSanitizer may abort with “unexpected memory mapping”; running it as setarch -R ./a.out, which disables address randomisation for that run, fixes it.) Then fix it without an atomic: give each thread a local counter and add both to the total after join().

View source on GitHub →