Threads, mutexes and atomics
Running work in parallel, and the data race that silently loses updates when two threads share a counter.
- 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:
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().