← C++ roadmap

Topic 14 of 27 · Expert

Concurrency: Threads, Mutex & Atomics

std::thread, jthread, mutex, lock_guard, atomic and async.

Concept

std::thread runs a function in parallel; std::jthread (C++20) joins automatically on destruction.

Shared mutable data needs synchronisation: std::mutex with std::lock_guard / std::scoped_lock, or std::atomic for simple counters.

std::async and std::future return results from background tasks. Condition variables let threads wait for events.

Code (C++20)

#include <atomic>
#include <future>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

int main() {
    std::atomic<int> hits{0};
    std::mutex m;
    std::vector<int> log;

    {
        std::vector<std::jthread> workers;
        for (int t = 0; t < 4; ++t)
            workers.emplace_back([&, t] {
                for (int i = 0; i < 1000; ++i) ++hits;
                std::scoped_lock lock(m);
                log.push_back(t);
            });
    }   // jthreads join here

    auto f = std::async(std::launch::async, [] { return 6 * 7; });
    std::cout << hits << ' ' << log.size() << ' ' << f.get() << '\n';  // 4000 4 42
}

Remember

  • Data race = undefined behaviour.
  • Lock with RAII guards, never manual unlock.
  • scoped_lock locks multiple mutexes deadlock-free.

Interview questions

mutex vs atomic?

atomic makes single operations on one variable indivisible without locks; a mutex protects larger critical sections touching several variables.

How do you avoid deadlock?

Lock in a consistent order, use std::scoped_lock for multiple mutexes, keep critical sections short and avoid calling unknown code while holding a lock.

Practise C++ with the AI mentor

Lesson test

Take an 8-question test on “Concurrency: Threads, Mutex & Atomics” — concepts, output prediction, bug spotting and interview questions.

Can't find a C++ topic you need for exams or placements? Request it and we'll add it.