Concurrency
Concurrency
Threads, mutexes, atomics, async work, and synchronization basics.
Concurrency
Threads, mutexes, atomics, async work, and synchronization basics.
std::thread worker([] {
do_work();
});
worker.join();
std::mutex m;
int counter = 0;
void increment() {
std::lock_guard<std::mutex> lock(m);
++counter;
}
std::condition_variable cv;
std::mutex m;
bool ready = false;
Use cv.wait(lock, predicate) to avoid spurious wake-up bugs.
std::atomic<int> count{0};
count.fetch_add(1, std::memory_order_relaxed);
auto future = std::async(std::launch::async, compute);
auto result = future.get();
join() or detach() a std::thread.std::jthread and cancellationstd::jthread worker([](std::stop_token stop) {
while (!stop.stop_requested()) {
tick();
}
});
std::jthread joins automatically on destruction.std::stop_token for cooperative cancellation.std::shared_mutex: many readers, one writer.std::latch: one-shot coordination point.std::barrier: repeated phase synchronization.std::counting_semaphore: bound access to a resource pool.memory_order_relaxed is for counters and statistics, not for publishing complex state.