Concurrency

Concurrency

Threads, mutexes, atomics, async work, and synchronization basics.

Concurrency

Basic thread creation

std::thread worker([] {
    do_work();
});
worker.join();

Mutex and lock guard

std::mutex m;
int counter = 0;

void increment() {
    std::lock_guard<std::mutex> lock(m);
    ++counter;
}

Condition variables

std::condition_variable cv;
std::mutex m;
bool ready = false;

Use cv.wait(lock, predicate) to avoid spurious wake-up bugs.

Atomics

std::atomic<int> count{0};
count.fetch_add(1, std::memory_order_relaxed);

Futures and async

auto future = std::async(std::launch::async, compute);
auto result = future.get();

Best-practice reminders

std::jthread and cancellation

std::jthread worker([](std::stop_token stop) {
    while (!stop.stop_requested()) {
        tick();
    }
});

More synchronization tools

Memory ordering guidance