Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. A mutex: taking turns
    4. Critical sections: keep them short
    5. Two mutexes: deadlock
    6. Atomics: one indivisible step
    7. Memory order
    8. Waiting for work: std::condition_variable
    9. std::latch: wait until N things are done
    10. Which one should I use?
    11. Under the hood
    12. False sharing
    13. Common pitfalls
    14. Two atomic steps aren’t one
    15. Try it yourself

    Module 10 · Concurrency

    10.2Mutexes and atomics

    Share data between threads without a data race. Lock a std::mutex with std::scoped_lock, avoid deadlock, use std::atomic for counters and flags, wait for work with std::condition_variable, and keep threads off each other's cache lines.

    About 30 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. A mutex: taking turns
    4. Critical sections: keep them short
    5. Two mutexes: deadlock
    6. Atomics: one indivisible step
    7. Memory order
    8. Waiting for work: std::condition_variable
    9. std::latch: wait until N things are done
    10. Which one should I use?
    11. Under the hood
    12. False sharing
    13. Common pitfalls
    14. Two atomic steps aren’t one
    15. Try it yourself

    Key terms

    mutex
    A lock that only one thread can hold at a time (std::mutex, from <mutex>). A thread that tries to lock it while another holds it waits.
    critical section
    The code that runs while a mutex is held. Only one thread at a time can be inside it.
    std::lock_guard and std::scoped_lock
    RAII locks: the constructor locks the mutex, the destructor unlocks it. std::scoped_lock can lock several mutexes at once.
    deadlock
    Threads that each wait for a lock another one holds, so none of them can ever go on.
    std::atomic<T>
    A type from <atomic> whose operations, such as fetch_add, load and store, happen as one indivisible step, so threads can share it without a data race.
    memory order
    How much an atomic operation also orders the memory accesses around it. The default, std::memory_order_seq_cst, is the strictest; std::memory_order_relaxed only keeps the atomic itself correct.
    std::condition_variable
    Lets a thread sleep until another thread changes some shared state and notifies it. Used with a mutex and std::unique_lock.
    false sharing
    Threads that write different variables in the same cache line slow each other down, because the cores keep passing that line back and forth.

    Threads and jthread ended with two threads adding to the same int and ThreadSanitizer reporting a data race. Threads often do need to share something: a total, a queue of work, a flag that says “stop”. This lesson shows the two basic tools for sharing safely. A mutex makes threads take turns; an atomic makes one small operation indivisible.

    In 30 seconds

    • Lock a std::mutex around every use of shared data, with std::scoped_lock lock(m); so it’s unlocked on every path out.
    • Two mutexes locked in different orders by different threads can deadlock. Lock them together: std::scoped_lock lock(a, b);.
    • For a single counter or flag, std::atomic<int> is simpler and faster: fetch_add, load, store.
    • To wait until there’s work, use a std::condition_variable. Keep each thread’s busy variables in separate cache lines.

    A mutex: taking turns

    A std::mutex has two operations: lock() and unlock(). Only one thread can hold the lock. Any other thread that calls lock() waits until the holder unlocks. Put every access to total between them, reads included, and the two threads can no longer interleave their loads and stores. A read without the lock is still a data race, even if every write takes it.

    Calling lock() and unlock() yourself is easy to get wrong: an early return or an exception skips the unlock, and every other thread waits forever. So use an RAII lock. std::lock_guard locks in its constructor and unlocks in its destructor. Here is the race from the last lesson, fixed, and run under ThreadSanitizer:

    #include <mutex>
    #include <print>
    #include <thread>
    
    int main() {
        int total = 0;
        std::mutex total_mutex;
        auto count = [&total, &total_mutex] {
            for (int i = 0; i < 100'000; ++i) {
                std::lock_guard lock(total_mutex);
                ++total;
            }
        };
        {
            std::jthread a(count);
            std::jthread b(count);
        }
        std::println("{}", total);
    }

    Output

    200000

    ThreadSanitizer reports nothing now, and the total is right every run. std::lock_guard lock(total_mutex); works out the template argument from the mutex (class template argument deduction); it’s short for std::lock_guard<std::mutex>.

    Critical sections: keep them short

    The code that runs while the lock is held, here ++total, is the critical section. Only one thread can be in it, so time spent there is time the other threads wait. The example above locks 200,000 times to do almost nothing each time: correct, but slow. Do the real work outside the lock, in local variables, and lock only to combine the results. std::scoped_lock (C++17) is the general version of lock_guard: it locks one mutex, or several at once. Use it by default; the rest of this lesson does.

    Two mutexes: deadlock

    Each Account has its own mutex. transfer locks the source, then the destination. Two transfers in opposite directions lock the same two mutexes in opposite orders. If they run at the same time, the first thread holds a and waits for b while the second holds b and waits for a. Neither can ever go on: a deadlock, and the program hangs.

    This run doesn’t hang, because the second transfer starts only after the first has finished. ThreadSanitizer still sees the two orders and reports a lock-order inversion, a deadlock waiting for unlucky timing:

    #include <mutex>
    #include <thread>
    
    struct Account {
        std::mutex m;
        int balance = 100;
    };
    
    void transfer(Account& from, Account& to, int amount) {
        std::lock_guard lock_from(from.m);
        std::lock_guard lock_to(to.m);
        from.balance -= amount;
        to.balance += amount;
    }
    
    int main() {
        Account a;
        Account b;
        std::jthread([&a, &b] { transfer(a, b, 10); }).join();
        std::jthread([&a, &b] { transfer(b, a, 20); }).join();
    }

    This fails when it runs

    WARNING: ThreadSanitizer: lock-order-inversion (potential deadlock)
      Cycle in lock order graph: M0 (0x…) => M1 (0x…) => M0
    
      Mutex M1 acquired here while holding mutex M0 in thread T1:
        #0 pthread_mutex_lock
           … 3 frames inside the standard library
        #4 transfer(Account&, Account&, int) main.cpp:11
        #5 operator() main.cpp:19
           … 6 frames inside the standard library
    
      Mutex M0 acquired here while holding mutex M1 in thread T2:
        #0 pthread_mutex_lock
           … 3 frames inside the standard library
        #4 transfer(Account&, Account&, int) main.cpp:11
        #5 operator() main.cpp:20
           … 6 frames inside the standard library
    
      Thread T1 (finished) created by main thread at:
        #0 pthread_create
           … 2 frames inside the standard library
    
      Thread T2 (running) created by main thread at:
        #0 pthread_create
           … 2 frames inside the standard library
    
    SUMMARY: ThreadSanitizer: lock-order-inversion (potential deadlock) gthr-default.h:795 in __gthread_mutex_lock(pthread_mutex_t*)

    Read the report from the top. “Cycle in lock order graph: M0 => M1 => M0” is the problem in one line: one thread took M1 while holding M0, and another took M0 while holding M1. The next two blocks show where: both at main.cpp:11, the second lock_guard in transfer, called from line 19 in thread T1 and from line 20 in thread T2.

    The fix is to lock both mutexes in one step. std::scoped_lock with two mutexes uses a deadlock-avoidance algorithm: it never waits for one while holding the other. When you can’t lock everything at once, agree on one order for all code, for example always the account with the smaller id first. Here the two transfers really run at the same time:

    #include <mutex>
    #include <print>
    #include <thread>
    
    struct Account {
        std::mutex m;
        int balance = 100;
    };
    
    void transfer(Account& from, Account& to, int amount) {
        std::scoped_lock lock(from.m, to.m);
        from.balance -= amount;
        to.balance += amount;
    }
    
    int main() {
        Account a;
        Account b;
        {
            std::jthread first([&a, &b] { transfer(a, b, 10); });
            std::jthread second([&a, &b] { transfer(b, a, 20); });
        }
        std::println("{} {}", a.balance, b.balance);
    }

    Output

    110 90

    Atomics: one indivisible step

    A mutex protects any amount of code. When the shared state is one number or one flag, std::atomic<T> from <atomic> is simpler. Its operations happen as one step that no other thread can see half-done:

    • fetch_add(n) adds n and returns the value from before. ++x and x += n on an atomic do the same.
    • load() reads the value; store(v) writes it.

    Atomics are a good way to hand out work. Each thread takes the next unclaimed index with fetch_add(1), so no two threads ever get the same one, and a thread that finishes early takes more:

    #include <atomic>
    #include <print>
    #include <string_view>
    #include <thread>
    #include <vector>
    
    int main() {
        std::vector<std::string_view> reads = {"GATTACA", "GGCC", "ATAT",
                                               "CGCGCG",  "TTTA", "GCAT"};
        std::vector<std::size_t> lengths(reads.size());
        std::atomic<std::size_t> next{0};
        {
            std::vector<std::jthread> workers;
            for (int t = 0; t < 3; ++t) {
                workers.emplace_back([&reads, &lengths, &next] {
                    for (std::size_t i = next.fetch_add(1); i < reads.size();
                         i = next.fetch_add(1)) {
                        lengths[i] = reads[i].size();
                    }
                });
            }
        }
        std::println("{} (next = {})", lengths, next.load());
    }

    Output

    [7, 4, 4, 6, 4, 4] (next = 9)

    Each of the three threads stops when its fetch_add returns an index past the end, so next ends at 6 + 3 = 9. Which thread handled which read changes between runs; the result doesn’t. A std::atomic<bool> makes the stop flag a plain std::thread needs: the worker loops while (!stop.load()), and another thread ends the loop with stop.store(true).

    Memory order

    Each atomic operation takes an optional memory order. The default, std::memory_order_seq_cst (“sequentially consistent”), is the easiest to reason about: all threads agree on one order of all such operations, and the reads and writes around them can’t be moved across them. For a counter that nothing else depends on, std::memory_order_relaxed is enough: count.fetch_add(1, std::memory_order_relaxed) keeps the count exact but promises nothing about other memory. The false-sharing example below uses it. Between those two sit std::memory_order_release and acquire: a store with release followed by a load with acquire that sees it guarantees the loading thread also sees everything the storing thread wrote before the store. That’s how one thread hands a finished buffer to another. Use the default unless you’ve measured a need and can explain why a weaker order is correct.

    Waiting for work: std::condition_variable

    A thread that waits for work could check a queue in a loop, but that keeps a core busy doing nothing. A std::condition_variable (from <condition_variable>) lets it sleep until another thread calls notify_one(). Here a producer pushes reads into a queue and a consumer thread handles them. std::queue (from <queue>) adds at the back with push and takes from the front with front and pop:

    #include <condition_variable>
    #include <mutex>
    #include <optional>
    #include <print>
    #include <queue>
    #include <string>
    #include <thread>
    
    class ReadQueue {
    public:
        void push(std::string read) {
            std::scoped_lock lock(mutex_);
            reads_.push(std::move(read));
            ready_.notify_one();
        }
        void close() {
            std::scoped_lock lock(mutex_);
            closed_ = true;
            ready_.notify_all();
        }
        // Waits for a read; std::nullopt once closed and empty.
        std::optional<std::string> pop() {
            std::unique_lock lock(mutex_);
            ready_.wait(lock, [this] { return !reads_.empty() || closed_; });
            if (reads_.empty()) {
                return std::nullopt;
            }
            std::string read = std::move(reads_.front());
            reads_.pop();
            return read;
        }
    
    private:
        std::mutex mutex_;
        std::condition_variable ready_;
        std::queue<std::string> reads_;
        bool closed_ = false;
    };
    
    int main() {
        ReadQueue queue;
        std::size_t bases = 0;
        std::jthread consumer([&queue, &bases] {
            while (std::optional<std::string> read = queue.pop()) {
                bases += read->size();
            }
        });
        for (std::string read : {"GATTACA", "GGCC", "ATAT"}) {
            queue.push(read);
        }
        queue.close();
        consumer.join();
        std::println("{} bases", bases);
    }

    Output

    15 bases

    wait needs a std::unique_lock, a lock that can be unlocked and locked again while it exists. wait(lock, condition) does three things in a loop: if the condition is true it returns, still holding the lock; otherwise it unlocks and sleeps, and when woken, locks again and checks again. Checking the condition under the lock means a push can’t slip in between the check and the sleep. close() lets the consumer know there’s nothing more coming, so it can finish instead of waiting forever.

    std::latch: wait until N things are done

    std::latch (C++20, <latch>) is a one-time countdown. Each thread calls count_down(); wait() returns once the count reaches zero. Unlike join, the threads can keep running afterwards:

    #include <latch>
    #include <print>
    #include <thread>
    #include <vector>
    
    std::vector<int> ready_parts(3);
    std::latch parts_done(3);
    std::vector<std::jthread> workers;
    for (int t = 0; t < 3; ++t) {
        workers.emplace_back([&ready_parts, &parts_done, t] {
            ready_parts[t] = (t + 1) * 10;
            parts_done.count_down(); // the thread could go on with other work
        });
    }
    parts_done.wait();
    std::println("{}", ready_parts);

    Output

    [10, 20, 30]

    Which one should I use?

    WhatWhenWhyHow
    Nothing sharedEach thread can write its own slot or variable.No locks, no waiting, no races. Combine after join.partial[t] = …;
    std::atomic<T>One counter, index or flag.One indivisible step, no lock.count.fetch_add(1);
    std::mutex + std::scoped_lockSeveral values that must change together, or a container.Everything in the critical section happens as one unit.std::scoped_lock lock(m);
    std::condition_variableA thread must wait until there’s work or a change.It sleeps instead of checking in a loop.cv.wait(lock, [&] { return ready; });
    std::latchWait until N tasks are done, once.Simpler than a counter and a condition variable.done.count_down(); / done.wait();

    Rule of thumb: share as little as you can. Use an atomic for one number, a mutex for anything bigger, and lock several mutexes with one std::scoped_lock.

    Under the hood

    On x86-64, an atomic add is one instruction with a lock prefix, which makes the core own the memory until the add is done. Without std::atomic, the same add has no prefix, and another core can change the value in between:

    #include <atomic>
    
    void add_atomic(std::atomic<int>& count) {
        count.fetch_add(1);
    }
    
    void add_plain(int& count) {
        ++count;
    }

    Assembly (GCC 15, -O2)

    add_atomic(std::atomic<int>&):
        lock add DWORD PTR [rdi], 1
        ret
    add_plain(int&):
        add     DWORD PTR [rdi], 1
        ret

    On Linux, a std::mutex is built on an atomic too. Locking a free mutex is one atomic operation; only when the mutex is taken does the thread ask the operating system to put it to sleep until it’s unlocked. That’s why an uncontended lock is cheap and a contended one is slow.

    False sharing

    Cores don’t move single bytes between them: they move whole cache lines, 64 bytes on this platform. When one core writes, it takes the line away from every other core. Two counters in the same line, each written by its own thread, make the line bounce between the cores, even though the threads never touch the same counter. alignas(std::hardware_destructive_interference_size) (from <new>) starts each counter on its own line:

    #include <atomic>
    #include <chrono>
    #include <new>
    #include <print>
    #include <thread>
    
    struct SameLine {
        std::atomic<long> a{0};
        std::atomic<long> b{0};
    };
    
    struct OwnLines {
        alignas(std::hardware_destructive_interference_size) std::atomic<long> a{0};
        alignas(std::hardware_destructive_interference_size) std::atomic<long> b{0};
    };
    
    template <typename Counters>
    double milliseconds() {
        Counters c;
        auto bump = [](std::atomic<long>& n) {
            for (int i = 0; i < 10'000'000; ++i) {
                n.fetch_add(1, std::memory_order_relaxed);
            }
        };
        auto start = std::chrono::steady_clock::now();
        {
            std::jthread x(bump, std::ref(c.a));
            std::jthread y(bump, std::ref(c.b));
        }
        std::chrono::duration<double, std::milli> took =
            std::chrono::steady_clock::now() - start;
        return took.count();
    }
    
    int main() {
        std::println("same line: {:.0f} ms", milliseconds<SameLine>());
        std::println("own lines: {:.0f} ms", milliseconds<OwnLines>());
    }

    Output from one run (it varies)

    same line: 166 ms
    own lines: 39 ms

    In this run, the counters on their own lines finished about four times faster. The numbers depend on the machine; the gap usually shows up on any machine with several cores. Per-thread slots in a vector, as in Parallel work, have the same problem when threads write them in a loop: add into a local variable and write the slot once.

    Common pitfalls

    Two atomic steps aren’t one

    Every operation on an atomic is indivisible, but two operations in a row aren’t. This loop loads, adds 1 and stores, so another thread can store in between and that update is lost. It isn’t a data race, so ThreadSanitizer stays quiet, but the total is wrong:

    #include <atomic>
    #include <print>
    #include <thread>
    
    std::atomic<int> total{0};
    auto count = [&total] {
        for (int i = 0; i < 100'000; ++i) {
            // Two steps: another thread can store between them.
            total.store(total.load() + 1);
        }
    };
    {
        std::jthread a(count);
        std::jthread b(count);
    }
    std::println("{}", total.load());

    Output from one run (it varies)

    140546

    Use one operation that does the whole change: total.fetch_add(1) or ++total. For changes no single operation covers, use a mutex.

    Try it yourself

    Try it yourself

    Two threads each count the reads that contain "GC" in half of reads and add to one shared found. The starter uses one thread, so it’s correct; make the two halves run on two std::jthreads without a data race.

    #include <print>
    #include <string_view>
    #include <vector>
    
    int main() {
        std::vector<std::string_view> reads = {"GATTACA", "GGCC", "AGCT", "CGCA"};
        int found = 0;
        auto scan = [&reads, &found](std::size_t first, std::size_t last) {
            for (std::size_t i = first; i < last; ++i) {
                if (reads[i].contains("GC")) {
                    ++found;
                }
            }
        };
        scan(0, 2);
        scan(2, 4);
        std::println("{}", found);
    }

    Expected output

    3
    Show a hint

    Make found a std::atomic<int> from <atomic>, and increase it with ++found or found.fetch_add(1). Read it with load() after the threads have joined.

    Show a solution
    #include <atomic>
    #include <print>
    #include <string_view>
    #include <thread>
    #include <vector>
    
    int main() {
        std::vector<std::string_view> reads = {"GATTACA", "GGCC", "AGCT", "CGCA"};
        std::atomic<int> found{0};
        auto scan = [&reads, &found](std::size_t first, std::size_t last) {
            for (std::size_t i = first; i < last; ++i) {
                if (reads[i].contains("GC")) {
                    ++found;
                }
            }
        };
        {
            std::jthread a(scan, 0, 2);
            std::jthread b(scan, 2, 4);
        }
        std::println("{}", found.load());
    }

    ++found on a plain int is a load, an add and a store, so two threads can both read the same value and lose an update. On a std::atomic<int>, ++found is one indivisible fetch_add, so every match is counted. The block makes both jthreads join before main reads the total.

    Saved in this browser only.