Concurrency Basics
Concurrency Basics
Start threads safely, protect shared data, and avoid common synchronization mistakes.
Concurrency Basics
Start threads safely, protect shared data, and avoid common synchronization mistakes.
std::thread worker([] {
do_work();
});
worker.join();
std::mutex m;
int total = 0;
void add() {
std::lock_guard<std::mutex> lock(m);
++total;
}
Make correctness obvious first. Parallel speedups matter only after the sequential design is correct.
std::jthread for owned worker threadsstd::jthread worker([](std::stop_token stop) {
while (!stop.stop_requested()) {
poll_once();
}
});
std::jthread joins on destruction and supports cooperative cancellation through std::stop_token.
Always wait with a predicate so spurious wakeups do not break correctness.
cv.wait(lock, [] { return ready; });
Use atomics for small shared states such as counters, flags, and state transitions. Reach for mutexes when you need to protect larger invariants.