Module 8 · Lesson 40 of 90

Threads, mutexes, and deadlock

Create and join C++ threads, protect shared data with mutexes and RAII lock guards, and avoid deadlock with lock ordering and scoped_lock.

  • Beginner to advanced
  • 12 min read
  • 40 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with g++ (GCC 13); a terminal; optionally a Raspberry Pi 4 or 5 to see true multi-core parallelism

Your place in the module
By the end you can 4 objectives
  • Create std::thread objects from functions and lambdas and manage their lifetime with join, detach, and move
  • Explain why a data race is undefined behavior and detect one with ThreadSanitizer
  • Protect shared state with std::mutex and choose between lock_guard, unique_lock, and scoped_lock
  • Avoid deadlock using a lock order or the deadlock-avoidance algorithm in std::scoped_lock and std::lock
Video coming soonThreads, mutexes, and deadlock
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Shrinking the C++ runtime footprint
  • Including <iostream> makes the program depend on libstdc++ and its locale and stream machinery; on GCC 13 the stream setup lives in the library, not in a constructor per source file
  • With no new_handler, a failed plain operator new throws std::bad_alloc, and in a program built with -fno-exceptions nothing can catch it, so the program aborts; std::set_new_handler installs a hook that runs first
  • Freestanding C++ guarantees only a small required header subset; a Linux application is hosted
01

One process, several threads

3 min read

In the last lesson you trimmed the C++ runtime for embedded builds. This lesson starts concurrency: std::thread, the data races threads can cause, mutexes with lock guards, and lock ordering with scoped_lock to avoid deadlock.

An embedded Linux program rarely does one thing at a time. A sensor gateway reads a serial device, serves network clients, and writes a log, and none of these may block the others for long. Threads are the standard tool: several execution paths inside one process, all sharing the same address space. Linux has exposed this through POSIX threads for decades; the interface was standardized in 1995 as POSIX.1c and is summarized in the pthreads(7) man page. C++11 brought the same capability into the standard library as std::thread. On Ubuntu 24.04 (GCC 13, glibc 2.39), std::thread is a thin wrapper over pthread_create: every C++ thread is a real kernel task, and you can see the tasks of a process listed under /proc/<pid>/task/.

What threads share and what they keep private is the whole story of this lesson. All threads in a process see the same code, the same global variables, the same heap, and the same open file descriptors. Each thread has its own stack, its own registers, and its own errno. Sharing the heap and globals is what makes threads useful (no copying data between workers) and dangerous (two workers can touch the same object at the same instant).

One address space, private stackshighMain thread stackprivate to main threadThread 2 stackmmap region, private(free)Heapshared by all threadsData / BSSglobals, sharedlowTextprogram code, sharedhighMain thread stackprivate to main threadThread 2 stackmmap region, private(free)Heapshared by all threadsData / BSSglobals, sharedlowTextprogram code, shared
One address space: every thread has a private stack, but the heap, globals and code are shared

A std::thread is created from a callable plus its arguments. The callable can be a free function, a lambda, or a member function pointer paired with an object:

cpp
#include <iostream>
#include <thread>

void sample(int id) {
    std::cout << "worker " << id << " done\n";
}

int main() {
    std::thread t1(sample, 1);
    std::thread t2([]{ std::cout << "lambda done\n"; });
    std::thread t3 = std::move(t1);   // ownership moves; t1 is now empty
    t3.join();
    t2.join();
}
bash
g++ -Wall -Wextra -std=c++17 -pthread threads.cpp -o threads
./threads

The -pthread flag is the correct way to build threaded programs with GCC on Linux: it enables thread-aware code generation and links thread support. In our two runs the output was worker 1 done then lambda done both times, but nothing guarantees that order. Both lines print, but their order can differ between runs, and because each << is a separate call, characters from the two lines can even interleave. Keep that observation in mind: it is the smallest possible demonstration of the problem this lesson solves.

Arguments passed to the constructor are copied into storage owned by the new thread, so the thread never depends on the caller's stack for them. If you really want the thread to use an existing object, pass std::ref(obj) and make sure the object outlives the thread. The same caution applies to lambdas: capturing a local by reference is only safe if you join before that local dies.

The constructor starts the thread immediately; the std::thread object is only a handle to it. Three operations manage that handle. join() blocks the calling thread until the thread function returns, and afterwards the handle is empty. detach() releases the handle and lets the thread run on independently; you can never join it again. joinable() reports whether the handle still owns a thread of execution: true after construction, false after join(), detach(), or a move out of the object.

Like unique_ptr from earlier in this module, std::thread is move-only: copying is deleted because two handles cannot own one thread. Moving transfers ownership and leaves the source non-joinable, which is how you return a thread from a factory function or store threads in a container.

A joinable thread must never reach its destructor

If a std::thread object is destroyed while still joinable, its destructor calls std::terminate and the program aborts. The standard forces you to decide: join() (wait for the work) or detach() (let it run free) before the handle goes out of scope. Detached threads are risky in embedded daemons: they can outlive main's locals and touch destroyed objects. Prefer joining every thread during shutdown.

Four cores means true parallelism

A Raspberry Pi 4 has four Cortex-A72 cores and a Pi 5 has four Cortex-A76 cores, so up to four threads execute at the same physical instant. On a single-core board the kernel interleaves threads instead. Write code that assumes true parallelism: a race that hides on one core will show up on four.

02

Data races: unsynchronized sharing is undefined behavior

3 min read

Here is the classic demonstration. Two threads each increment a shared counter 100000 times:

cpp
long counter = 0;              // shared by both threads

void bump() {
    for (int i = 0; i < 100000; ++i) {
        ++counter;             // read, add, write: three steps
    }
}

Run bump in two threads, join both, print counter. You might expect 200000. Built as shown (no optimization flag), five runs of this program on Ubuntu 24.04 printed 101601, 103077, 112976, 102723 and 109721: a different, smaller number every time. Built with -O2 the same source printed 200000 three times in a row, because the compiler folded the loop into one addition; the data race is still there, the output just stopped showing it. The reason for the lost updates is that ++counter is a read-modify-write: load the old value, add one, store the result. If both threads load the same old value before either stores, both write the same new value and one increment is lost. Even where the compiler emits a single add-to-memory instruction on x86-64, that instruction is not atomic with respect to another core.

A lost updateThread AcounterThread Bread nread nwrite n + 1write n + 11. Thread A → counterread n2. Thread B → counterread n3. Thread A → counterwrite n + 14. Thread B → counterwrite n + 1
Both threads read the same value n and both write n+1: two increments happened, only one survived

This is a . The C++ standard does not say a data race produces a stale value; it says the program has undefined behavior. That is stronger than it sounds. The compiler is allowed to assume data races do not exist, and it optimizes on that assumption: it may keep a shared variable in a register, reorder reads and writes, or hoist a read out of a loop. A spin loop like while (!done) {} waiting for another thread to set done can be compiled into a loop that reads done once and then spins forever, even though the other thread did write it. (Whether it happens depends on the compiler and flags: a small test of that loop built with GCC 13 at -O2 happened to exit, which is one more allowed behavior of undefined code.) Adding volatile does not fix this: volatile is for memory-mapped I/O (a later lesson), not for thread synchronization.

The practical rule for this lesson: every shared mutable object is protected by a mutex, on every access, read or write. The formal machinery behind that rule (conflicting evaluations and the happens-before relation) is the subject of lesson M8-S06B, and lock-free alternatives with atomics come after it. You do not need the formal model to write correct mutex-based code, but you do need to know that "it printed the right answer" proves nothing.

You can find races mechanically with ThreadSanitizer, which GCC 13 supports:

bash
g++ -Wall -Wextra -std=c++17 -pthread -g -fsanitize=thread race.cpp -o race
./race

The report starts with WARNING: ThreadSanitizer: data race, then shows a read and a previous write of size 8 inside bump() from two threads, and the line Location is global 'counter' of size 8; addresses and thread numbers on your machine will differ.

ThreadSanitizer on WSL2

On some WSL2 kernels ThreadSanitizer aborts at startup with a fatal memory-mapping error because of how the address space is laid out. If that happens, run the same binary in a full Ubuntu VM, where it works normally.

03

Mutexes and lock guards

4 min read

A std::mutex (header <mutex>) has two core operations: lock() blocks until the calling thread owns the mutex exclusively, and unlock() releases it. The code between them is a . While one thread holds the mutex, every other thread that calls lock() waits. On Linux, libstdc++ builds std::mutex on pthread_mutex_t, which uses the futex(2) system call: an uncontended lock is just a user-space atomic operation with no kernel entry, and only actual waiting goes into the kernel. That is why a mutex around a short critical section is cheap enough to use freely.

Calling lock() and unlock() by hand is a bug factory. An early return, a break, or an exception thrown between them (and you know from the exceptions lesson how unwinding skips straight past your unlock()) leaves the mutex locked forever, and every other thread blocks on it. The fix is the RAII pattern you already know: put the lock in an object whose destructor unlocks.

C++ gives you three guards. std::lock_guard (C++11) locks in its constructor, unlocks in its destructor, and does nothing else: no early unlock, no moving, minimal state. std::unique_lock (C++11) also owns one mutex but is flexible: it can be constructed without locking (std::defer_lock), it can unlock() and lock() again mid-scope, and it is movable. That flexibility is exactly what condition variables need in the next lesson, because waiting must temporarily release the mutex. std::scoped_lock (C++17) is the modern default: like lock_guard, but it can take several mutexes at once and acquires them without deadlock, and class template argument deduction lets you write std::scoped_lock lock(m); without naming the mutex type.

Guard Since Mutexes Movable Early unlock
std::lock_guard C++11 one no no
std::unique_lock C++11 one yes yes
std::scoped_lock C++17 one or more no no

Here is the counter race fixed. The guard's scope is one iteration, so the lock is held only for the increment:

cpp
#include <iostream>
#include <mutex>
#include <thread>

long counter = 0;
std::mutex m;

void bump() {
    for (int i = 0; i < 100000; ++i) {
        std::lock_guard<std::mutex> lock(m);
        ++counter;
    }
}

int main() {
    std::thread a(bump), b(bump);
    a.join();
    b.join();
    std::cout << counter << "\n";   // always exactly 200000
}

Build it with the same -pthread command as before. This program prints exactly 200000 on every run: each increment now happens while its thread owns the mutex, so no read-modify-write can interleave with another.

Step by stepRules for critical sections
  1. Name the invariant: decide which mutex protects which data, and write it down next to the data declaration.

  2. Always use a guard: never call lock()/unlock() by hand in application code.

  3. Keep the section short: do formatting, computation and I/O preparation outside the lock; inside, touch only the shared state.

  4. Never call unknown code under a lock: a callback or virtual call might take another mutex, or call back into you and take the same one.

  5. One lock per operation: if an operation must hold two mutexes, use std::scoped_lock (next section), not two nested guards in an ad-hoc order.

These rules are exactly what the practice lab needs. A thread-safe logger is a class with a std::mutex member and one locked write per message:

cpp
class Logger {
public:
    explicit Logger(std::ostream& out) : out_(out) {}
    void log(const std::string& line) {
        std::lock_guard<std::mutex> lock(m_);
        out_ << line << '\n';
    }
private:
    std::mutex m_;
    std::ostream& out_;
};

Because the whole line is written under one lock, lines never interleave, and the mutex member ties the protection to the object that owns the stream. To measure contention, have N threads each log a fixed number of messages and time the whole run with std::chrono::steady_clock (the monotonic clock, unaffected by wall-clock adjustments). The total line count is exactly N times the per-thread count, which is your correctness check. The wall time is your contention measurement: the locked write serializes all threads, so beyond some thread count, adding threads adds waiting, not throughput. The lab has you vary the thread count and, as an extension, move string formatting outside the lock and measure the difference.

Format outside, write inside

Building the message string (timestamps, number formatting, concatenation) can be the slowest step of logging. Do it before taking the lock, so the critical section contains only the write. Shorter critical sections mean less time other threads spend blocked.

Going deeperReader-writer synchronization with std::shared_mutex

A plain mutex excludes everyone, including threads that only read. When reads dominate and writes are rare (a configuration object read by every worker, updated once in a while), C++17 offers std::shared_mutex in <shared_mutex>. It has two modes: shared, where any number of readers hold it at once, and exclusive, where one writer holds it and excludes all readers and other writers.

cpp
#include <shared_mutex>

std::shared_mutex cfg_mutex;
Config cfg;   // shared configuration object

Config read_config() {
    std::shared_lock lock(cfg_mutex);   // shared mode
    return cfg;
}

void update_config(const Config& next) {
    std::lock_guard lock(cfg_mutex);    // exclusive mode
    cfg = next;
}

Readers use std::shared_lock, writers use std::lock_guard, std::unique_lock or std::scoped_lock, which take it exclusively. On Linux, libstdc++ implements it over pthread_rwlock_t. It is not a free win: the lock itself is heavier than std::mutex, and even shared acquisition writes to internal state, so many readers on many cores still bounce the same cache line. The standard does not mandate reader or writer priority, so do not assume writers cannot be starved. Use it when read sections are long enough and frequent enough to overlap; for a two-instruction read, a plain mutex is often faster. Measure, as the contention lab teaches.

04

Deadlock and lock ordering

5 min read

A mutex makes each critical section safe, but holding two mutexes introduces a new failure. Consider a transfer between two accounts, each with its own mutex:

cpp
struct Account {
    std::mutex m;
    long balance = 0;
};

void transfer(Account& from, Account& to, long amount) {
    std::lock_guard<std::mutex> l1(from.m);
    std::lock_guard<std::mutex> l2(to.m);
    from.balance -= amount;
    to.balance += amount;
}

Each individual lock is used correctly, yet the program can hang. Thread 1 calls transfer(a, b) and locks a.m. Thread 2 calls transfer(b, a) and locks b.m. Now thread 1 blocks waiting for b.m, which thread 2 holds, and thread 2 blocks waiting for a.m, which thread 1 holds. Neither can run, neither will release, and std::mutex::lock() has no timeout: they wait forever. With the two lock_guard lines back to back the window is tiny and the program usually finishes; we inserted a 50 ms sleep_for between the two locks to make the interleaving certain, and timeout 3 ./dead was then killed with exit status 124 on our machine. This is a .

The deadlock cycleThread 1Mutex AMutex BThread 2lock A:acquiredlock B:acquiredlock B: blockedlock A: blocked1. Thread 1 → Mutex Alock A: acquired2. Thread 2 → Mutex Block B: acquired3. Thread 1 → Mutex Block B: blocked4. Thread 2 → Mutex Alock A: blocked
Each thread holds one mutex and waits for the other: a cycle in which no thread can proceed

A hung program like this shows all its worker threads blocked in the kernel's futex wait. Attaching gdb -p <pid> and running thread apply all bt shows every thread's backtrace, and you will see them parked inside lock() calls on the two mutexes. That picture, a cycle of lock waits, is the signature of deadlock.

There are two standard cures. The first is a global lock order: assign every mutex a rank (for accounts, the account id) and require that any thread holding several locks always acquires them in rank order. If both transfers lock the lower-ranked account first, the cycle is impossible: one thread gets both locks and the other waits at the first one, holding nothing. Lock ordering scales to any number of mutexes, but it is a convention, and conventions break when a new contributor adds a path that locks in the wrong order.

The second cure is mechanical: let the library take the locks for you.

cpp
void transfer(Account& from, Account& to, long amount) {
    std::scoped_lock lock(from.m, to.m);   // both, deadlock-free
    from.balance -= amount;
    to.balance += amount;
}

std::scoped_lock with several mutexes is required by the standard to use a deadlock-avoidance algorithm, the same one as the free function std::lock(m1, m2). The algorithm's shape is try-and-back-off: lock one mutex, then try_lock() the next; if the try fails, release what you hold and retry, so no thread ever sits holding one lock while blocked on another. Because of this, the argument order does not matter: two threads calling scoped_lock(m1, m2) and scoped_lock(m2, m1) cannot deadlock with each other. If you need the locks without a scoped guard, call std::lock yourself and hand the already-locked mutexes to guards with std::adopt_lock:

cpp
std::lock(m1, m2);   // both locked, no deadlock
std::lock_guard<std::mutex> l1(m1, std::adopt_lock);
std::lock_guard<std::mutex> l2(m2, std::adopt_lock);

In practice, prefer designs that need only one mutex per operation: one mutex protecting both accounts, or one mutex per logger, removes the problem entirely. When an operation genuinely needs two locks, use std::scoped_lock rather than nested guards, and never call code you do not control while holding a lock, because it may take locks you cannot see. The practice exercises have you build the two-mutex deadlock, watch it hang under timeout, and fix it with scoped_lock. With one scoped_lock(from.m, to.m) in place of the two guards and the same sleep, the program finished normally and printed 95 105.

A mutex makes shared data safe, but it does not let a thread sleep until new data arrives: polling a queue in a locked loop burns CPU and still misses events between checks. The next lesson, "Condition variables and lost wakeups", answers how a thread waits for an event efficiently, and why the obvious implementation of that wait has a race of its own.

Key takeaways

  • Destroying a joinable std::thread calls std::terminate, so every thread must be joined or detached before its handle dies
  • Any data race makes the whole program undefined behavior, not just the value that was raced on
  • lock_guard, unique_lock, and scoped_lock release the mutex on every exit path, including exceptions
  • std::scoped_lock and std::lock acquire several mutexes with a deadlock-avoidance algorithm, so argument order does not matter
Reflect
  1. Explain to a colleague, in two sentences: create std::thread objects from functions and lambdas and manage their lifetime with join, detach, and move
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close