Skip to content
LeetQuant
QD06 Concurrency and Networking

QD06 · Concurrency and Networking · Lesson 1 of 5

Threads and Synchronisation

What a data race is and why it is undefined behaviour, std::thread, mutexes and the three lock wrappers, condition variables and spurious wakeups, deadlock and lock ordering, and a producer–consumer queue built from them.

18 min

The problem: shared memory without rules

Threads in one process share an address space. That is what makes them fast to communicate (no copying, no syscalls) and what makes them dangerous: two threads touching the same variable can interleave in ways no single-threaded reading of the code predicts.

The C++ memory model makes this precise. A data race is two accesses to the same memory location from different threads where

  1. at least one is a write,
  2. at least one is not atomic, and
  3. neither happens before the other (nothing such as a mutex or an atomic orders them).

A program with a data race has undefined behaviour. Not "a slightly wrong number": the compiler is allowed to assume races never happen, so it may keep a variable in a register, merge or reorder accesses, or tear a 64-bit write in two. Interviewers like this point because candidates often believe a race on an int is "benign".

Lost updates, demonstrated

x = x + 1 is three steps: load, add, store. If two threads both load 41, both store 42, and one increment is lost.

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

constexpr int kThreads = 4, kIters = 1'000'000;

template <typename Body>
void run(Body body) {
    std::vector<std::thread> ts;
    for (int t = 0; t < kThreads; ++t) ts.emplace_back(body);
    for (auto& th : ts) th.join();   // join, or std::terminate runs in ~thread
}

int main() {
    volatile long racy = 0;   // volatile only stops the compiler merging the adds; it is NOT synchronisation
    run([&] { for (int i = 0; i < kIters; ++i) racy = racy + 1; });

    long safe = 0;
    std::mutex m;
    run([&] {
        for (int i = 0; i < kIters; ++i) {
            std::lock_guard<std::mutex> lock(m);
            ++safe;
        }
    });
    std::cout << "racy = " << racy << "\nsafe = " << safe << '\n';
}

Built with c++ -std=c++20 -O2 -Wall -pthread and run three times on an 8-core Apple M1:

racy = 1781609      racy = 2023886      racy = 1253562
safe = 4000000      safe = 4000000      safe = 4000000

Roughly half to two thirds of the increments vanished, and the count changes every run. (Even with volatile this is still a data race and still undefined behaviour; volatile is for memory-mapped hardware, not threads.) The mutexed counter is always exactly 4,000,000.

Mutexes and the lock wrappers

A std::mutex gives mutual exclusion: at most one thread holds it. Unlocking a mutex happens before the next lock of the same mutex, so every write made inside one critical section is visible inside the next. That is the whole contract.

Never call lock()/unlock() by hand: an exception or early return leaks the lock. Use RAII wrappers:

WrapperUse it when
std::lock_guard<M>Lock for exactly the enclosing scope. Smallest and simplest.
std::unique_lock<M>You need to unlock early, relock, defer locking, move the lock, or pass it to a condition variable.
std::scoped_lock<M1, M2, ...>You need several mutexes at once without deadlock (C++17).

Cost. An uncontended lock/unlock is a pair of atomic read-modify-writes on one cache line, typically tens of nanoseconds. A contended lock is very different: the loser spins briefly, then sleeps in the kernel (a futex on Linux) and must be woken by a syscall and scheduled again, which costs microseconds. In latency-sensitive code the rule is: keep critical sections tiny, never do I/O or allocation while holding a lock, and avoid sharing at all on the hot path.

Condition variables

A mutex protects state; a condition variable lets a thread sleep until that state changes. The pattern is always the same:

std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [&] { return !queue.empty(); });   // predicate form

wait atomically releases the mutex and sleeps; on wake-up it reacquires the mutex before returning. The predicate form is equivalent to

while (!pred()) cv.wait(lock);

and the loop is mandatory for two reasons:

  • Spurious wakeups. The standard (and POSIX) allow wait to return without any notify. Implementations do this because it makes the wake-up path cheaper.
  • Stolen wakeups. Even after a genuine notify, another consumer may grab the mutex first and empty the queue before you run.

The notifier must change the shared state while holding the mutex, then call notify_one or notify_all (holding the lock during the notify is allowed; releasing it first avoids waking a thread that immediately blocks on the mutex). If the state is changed without the lock, a waiter can check the predicate, see false, and go to sleep just after the notify was sent: a lost wakeup, and the thread may sleep forever.

Deadlock and lock ordering

Deadlock needs four conditions at once (Coffman): mutual exclusion, hold-and-wait, no pre-emption of locks, and a circular wait. The practical fix is to break the cycle:

  1. Global lock order. Give every mutex a rank and always acquire in increasing rank. Two threads can then never each hold what the other wants.
  2. Acquire together. std::scoped_lock lock(a.m, b.m); uses a deadlock-avoidance algorithm (lock one, try the others, back off and retry), so the call order does not matter.
  3. Do not call unknown code under a lock. A callback that takes another lock silently creates an ordering you cannot see.
#include <iostream>
#include <mutex>
#include <thread>

struct Account {
    std::mutex m;
    long balance;
};

// Locks both accounts without deadlock, whatever order callers pass them in.
void transfer(Account& from, Account& to, long amount) {
    std::scoped_lock lock(from.m, to.m);
    from.balance -= amount;
    to.balance += amount;
}

int main() {
    Account a{{}, 1000}, b{{}, 1000};
    std::thread t1([&] { for (int i = 0; i < 100'000; ++i) transfer(a, b, 1); });
    std::thread t2([&] { for (int i = 0; i < 100'000; ++i) transfer(b, a, 1); });
    t1.join();
    t2.join();
    std::cout << a.balance << ' ' << b.balance << '\n';   // prints: 1000 1000
}

With two lock_guards taken as from then to, thread 1 locks a then wants b while thread 2 locks b then wants a: the textbook cycle, and the program hangs as soon as the timing lines up.

Worked example

a blocking producer–consumer queue

Write a thread-safe queue with push, a blocking pop, and close so the consumer can stop cleanly. One thread pushes 1,…,100,0001, \dots, 100{,}000; another pops until the queue is closed and drained. Check that every item arrives once.

Show solution

State: a std::queue, a closed flag, one mutex guarding both, one condition variable. The consumer's predicate is "there is an item or the queue is closed"; after waking it distinguishes the two by checking emptiness. std::optional signals end of stream.

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <optional>
#include <queue>
#include <thread>

template <typename T>
class BlockingQueue {
public:
    void push(T v) {
        {
            std::lock_guard<std::mutex> lock(m_);
            q_.push(std::move(v));
        }
        cv_.notify_one();  // notify after unlocking so the waiter can take the lock at once
    }
    void close() {
        {
            std::lock_guard<std::mutex> lock(m_);
            closed_ = true;
        }
        cv_.notify_all();
    }
    // Blocks until an item is available or the queue is closed and empty.
    std::optional<T> pop() {
        std::unique_lock<std::mutex> lock(m_);
        cv_.wait(lock, [&] { return !q_.empty() || closed_; });  // loops on spurious wakeups
        if (q_.empty()) return std::nullopt;
        T v = std::move(q_.front());
        q_.pop();
        return v;
    }
private:
    std::mutex m_;
    std::condition_variable cv_;
    std::queue<T> q_;
    bool closed_ = false;
};

int main() {
    BlockingQueue<int> q;
    long sum = 0;
    int count = 0;
    std::thread consumer([&] {
        while (auto v = q.pop()) { sum += *v; ++count; }
    });
    std::thread producer([&] {
        for (int i = 1; i <= 100'000; ++i) q.push(i);
        q.close();
    });
    producer.join();
    consumer.join();
    std::cout << "count = " << count << ", sum = " << sum << '\n';
}

Output:

count = 100000, sum = 5000050000

The expected sum is n(n+1)2=100,000×100,0012=5,000,050,000\frac{n(n+1)}{2} = \frac{100{,}000 \times 100{,}001}{2} = 5{,}000{,}050{,}000, so nothing was lost or duplicated.

Points to say out loud: sum and count are written only by the consumer and read by main after join, and join is a happens-before edge, so they need no lock. close uses notify_all because with several consumers every one must wake to see the flag. unique_lock is required because wait must unlock and relock it. The queue is unbounded; a production version adds a capacity and a second condition variable ("not full") so a fast producer blocks instead of exhausting memory.

Knowledge check

Why must a condition variable wait be written as while (!pred()) cv.wait(lock), or with the predicate overload, rather than a single if (!pred()) cv.wait(lock)?

Knowledge check

Two threads increment a shared volatile long without a lock, and the program usually prints the right total on your laptop. What is the most accurate statement?

Knowledge check

transfer(from, to) locks from.m then to.m with two lock_guards. Thread 1 calls transfer(a, b) while thread 2 calls transfer(b, a). Which change removes the deadlock?

Key takeaways

  • A data race (concurrent access, one a write, no happens-before) is undefined behaviour, not a small numerical error. volatile does not fix it.
  • Mutex unlock happens before the next lock, which is what makes writes in one critical section visible in the next. Use lock_guard, unique_lock or scoped_lock, never raw lock().
  • Uncontended locks cost tens of nanoseconds; contended ones put threads to sleep and cost microseconds. Keep critical sections short and off the hot path.
  • Always wait on a condition variable with a predicate; modify the predicate's state under the mutex to avoid lost wakeups.
  • Prevent deadlock with a global lock order or std::scoped_lock for multiple mutexes.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).