Modern C++ • C++20 baseline
Threads, Tasks, and Shared State
Run independent work concurrently and avoid shared mutable state where possible.
The standard thread library provides threads, futures, mutexes, and condition variables. Joining a thread ensures it has completed before dependent state is used. A future can communicate a result or exception. Concurrency correctness requires reasoning about lifetime, cancellation, and synchronization—not just starting another thread.
Key points
- A std::jthread joins automatically when it leaves scope.
- Prefer message passing or independent data over shared mutation.
Example
#include <iostream>
#include <thread>
int main() {
std::jthread worker([] {
std::cout << "work complete\n";
});
}
What to expect
The jthread is joined at scope exit, so the worker finishes before main returns.
Practice exercise
Pass a value into the worker and return a result using std::async/std::future instead of writing shared global state.
Key idea: Make thread lifetime and synchronization part of the design from the start.