# Threads, jthread, cooperative stop, and locks

> Why raw std::thread terminates on destruction, how std::jthread and stop_token provide cooperative cancellation, and how RAII locks, condition variables, latches, barriers, and semaphores coordinate concurrent execution.

- **Source:** C++ Atlas (https://cppatlas.com/topics/threads-jthread-and-locks)
- **Track:** Concurrency
- **Estimated reading time:** 9 minutes
- **ISO C++ clauses:** [thread.thread.class] (https://eel.is/c++draft/thread.thread.class), [thread.jthread.class] (https://eel.is/c++draft/thread.jthread.class), [thread.stoptoken] (https://eel.is/c++draft/thread.stoptoken), [thread.mutex.requirements] (https://eel.is/c++draft/thread.mutex.requirements), [thread.lock] (https://eel.is/c++draft/thread.lock), [thread.condition] (https://eel.is/c++draft/thread.condition), [thread.latch] (https://eel.is/c++draft/thread.latch), [thread.barrier] (https://eel.is/c++draft/thread.barrier), [thread.sema] (https://eel.is/c++draft/thread.sema), [thread.once.callonce] (https://eel.is/c++draft/thread.once.callonce)
- **cppreference links:** [std::thread](https://en.cppreference.com/w/cpp/thread/thread), [std::jthread](https://en.cppreference.com/w/cpp/thread/jthread), [std::stop_token](https://en.cppreference.com/w/cpp/thread/stop_token), [std::stop_source](https://en.cppreference.com/w/cpp/thread/stop_source), [std::scoped_lock](https://en.cppreference.com/w/cpp/thread/scoped_lock), [std::unique_lock](https://en.cppreference.com/w/cpp/thread/unique_lock), [std::shared_mutex](https://en.cppreference.com/w/cpp/thread/shared_mutex), [std::condition_variable_any](https://en.cppreference.com/w/cpp/thread/condition_variable_any), [std::latch](https://en.cppreference.com/w/cpp/thread/latch), [std::barrier](https://en.cppreference.com/w/cpp/thread/barrier), [std::counting_semaphore](https://en.cppreference.com/w/cpp/thread/counting_semaphore)
- **Prerequisites:** raii-and-resource-management, atomics-and-memory-ordering

Managing concurrency manually with raw OS threads breaks exception safety as soon as an early return or thrown exception leaves scope before `join()`. Modern C++ concurrency ties thread lifetime to RAII via `std::jthread`, pairs teardown with cooperative cancellation via `std::stop_token`, and layers deadlock-free lock wrappers and C++20 coordination primitives on top.

## The std::thread destructor trap and std::jthread

When a `std::thread` object is destroyed while still `joinable()`—meaning neither `join()` nor `detach()` was called—its destructor immediately invokes `std::terminate()`. The committee deliberately rejected implicit `detach()` (which leaves background workers reading destroyed stack locals) and implicit `join()` (which deadlocks if the worker waits on a condition the unwinding scope never fulfills). Even a simple helper function that creates a `std::thread`, throws an exception, and forgets a RAII wrapper aborts the process.

C++20 introduced `std::jthread` ("joining thread") to fix both lifetime and shutdown signaling. First, `~jthread()` automatically requests cancellation and joins the thread if `joinable()` is true. Second, `std::jthread` owns an internal `std::stop_source`. If your thread entry function takes `std::stop_token` as its first parameter, `std::jthread` automatically passes `get_stop_token()` without forcing you to allocate or wire a flag by hand.

> **Pitfall.** Always declare `std::jthread` as the **last** data member of any class holding mutexes, condition variables, or shared buffers used by that worker. Because class members are destroyed in reverse declaration order, placing `jthread` last guarantees `request_stop()` and `join()` complete *before* the mutex or queue is destroyed.

```cpp
#include <condition_variable>
#include <mutex>
#include <stop_token>
#include <thread>

class Worker {
    std::mutex mtx_;
    std::condition_variable_any cv_;
    bool ready_ = false;
    std::jthread thread_; // Declared LAST: stops and joins before mtx_/cv_ die

public:
    Worker()
        : thread_([this](std::stop_token st) {
              std::unique_lock lk(mtx_);
              if (!cv_.wait(lk, st, [this] { return ready_; })) {
                  return; // Stop requested while waiting
              }
          }) {}

    void signal_ready() {
        {
            std::scoped_lock lk(mtx_);
            ready_ = true;
        }
        cv_.notify_one();
    }
};
```

## Cooperative cancellation with stop_token

`std::stop_source`, `std::stop_token`, and `std::stop_callback` share a reference-counted atomic stop state. Calling `request_stop()` on the `stop_source` transitions the state once (atomically returning `true` only to the first caller) and wakes all observers holding matching `stop_token` copies. Unlike POSIX `pthread_cancel`, cancellation never injects asynchronous exceptions at arbitrary instructions; workers inspect `st.stop_requested()` at clean invariant boundaries and unwind destructors normally.

For blocking operations that cannot poll a boolean—such as waiting on a socket descriptor or an external C event loop—attach a `std::stop_callback`: its constructor registers a handler that executes when `request_stop()` fires. Crucially, if `stop_requested()` is **already** true when the `stop_callback` object is constructed, the callback runs synchronously inside the `stop_callback` constructor on the registering thread, guaranteeing zero missed cancellations.

> **Mental model.** A `stop_token` acts as a thread-safe, one-way cancellation channel with reactive callbacks—the caller requests shutdown, and the worker decides the safe point to unwind.

## Mutexes and RAII lock wrappers

Raw `mtx.lock()` and `mtx.unlock()` calls leak locked mutexes across early returns and exceptions. The standard library provides four RAII lock wrappers tailored to distinct locking patterns:

- **`std::lock_guard<M>`** acquires a single mutex on construction and releases it on destruction, with zero overhead and no move or manual-unlock methods.
- **`std::scoped_lock<Ms...>`** (C++17) generalizes `lock_guard` to variadic mutexes (`std::scoped_lock lk(m1, m2)`), using a deadlock-avoidance algorithm (`std::lock`) when given multiple locks while matching `lock_guard`'s zero overhead for a single mutex.
- **`std::unique_lock<M>`** supports deferred locking (`std::defer_lock`), timed or try locking (`std::try_to_lock`), adopting already-locked mutexes (`std::adopt_lock`), move transfer, manual `.unlock()`, and waiting on a `std::condition_variable`.
- **`std::shared_lock<SM>`** acquires shared reader access on `std::shared_mutex` or `std::shared_timed_mutex`, allowing concurrent readers while blocking exclusive `unique_lock` writers.

> **Pitfall.** Writing `std::scoped_lock(m1, m2);` or `std::unique_lock<std::mutex>(m);` without a variable name constructs an anonymous temporary that acquires the lock and immediately unlocks it at the semicolon, leaving the critical section unprotected.

| Lock Wrapper | Mutex Count | Movable & Deferrable | Manual Unlock | Primary Use Case |
| --- | --- | --- | --- | --- |
| `std::lock_guard` | Exactly 1 | No | No | Simple C++11 single-mutex critical section |
| `std::scoped_lock` | 0, 1, or many | No | No | Default single or deadlock-safe multi-mutex lock |
| `std::unique_lock` | 1 | Yes | Yes | Condition variables, lock transfer, early unlock |
| `std::shared_lock` | 1 shared mutex | Yes | Yes | Multiple concurrent readers with `shared_mutex` |

## Condition variables and spurious wakeups

`std::condition_variable` operates exclusively with `std::unique_lock<std::mutex>`, whereas `std::condition_variable_any` accepts any BasicLockable type (including `std::shared_lock` or custom locks) and provides stop-token-aware overloads such as `wait(lk, st, pred)`.

Calling bare `cv.wait(lk)` without a predicate invites two classic bugs: **lost wakeups** (the producer called `notify_one()` before the consumer reached `wait`, leaving the consumer sleeping forever) and **spurious wakeups** (operating-system futexes and scheduler signals may unblock a waiting thread even when no thread notified). Always pass a boolean predicate—`cv.wait(lk, [&] { return !queue.empty(); })`—which checks state under the lock in a loop before and after sleeping. When notifying, unlock the mutex before calling `notify_one()` or `notify_all()` whenever the condition variable itself remains alive, preventing the woken thread from immediately blocking on the still-held mutex.

> **Standardese.** Under `[thread.condition.condvar]`, `condition_variable::wait` may return spuriously without any notification; the predicate overload guarantees returning only when `bool(pred())` evaluates to `true` with `lock` reacquired (or, for `condition_variable_any::wait(lock, st, pred)`, when `st.stop_requested()` becomes `true`).

## Latches, barriers, semaphores, and call_once

C++20 added three lightweight coordination types alongside `std::call_once`:

- **`std::latch`** is a single-use downward counter (`count_down`, `wait`, `arrive_and_wait`). Any thread may call `count_down` multiple times, and waiting threads unblock once the counter reaches zero.
- **`std::barrier<CompletionFunction>`** coordinates reusable multi-phase work. When the phase arrival count reaches zero, the last arriving thread runs the completion step once before unblocking all participants and resetting the next phase (`arrive_and_wait`, `arrive_and_drop`). Under `[thread.barrier]`, `std::is_nothrow_invocable_v<CompletionFunction&>` is mandated (`noexcept`).
- **`std::counting_semaphore<LeastMaxValue>`** and **`std::binary_semaphore`** track available permits (`acquire`, `release`, `try_acquire`). Unlike `std::mutex`, semaphores impose **no thread ownership**: Thread A can `release()` a permit that Thread B later `acquire()`s, whereas unlocking a `std::mutex` from a thread that did not lock it is undefined behavior.
- **`std::once_flag` and `std::call_once`** guarantee exactly-once initialization per flag object across threads. Under `[thread.once.callonce]`, if an active invocation exits by throwing an exception, it counts as exceptional rather than returning, and another waiting invocation gets to retry.

```cpp
#include <barrier>
#include <latch>
#include <mutex>
#include <semaphore>
#include <shared_mutex>

void coordination_demo() {
    std::mutex a, b;
    {
        std::scoped_lock both(a, b); // Deadlock-free acquisition of two mutexes
    }

    std::shared_mutex rw;
    { std::shared_lock reader(rw); } // Concurrent reader access
    { std::unique_lock writer(rw); } // Exclusive writer access

    std::latch ready(1);
    ready.count_down();
    ready.wait();

    auto step_done = []() noexcept { /* runs once per phase */ };
    std::barrier phase(1, step_done);
    phase.arrive_and_wait();

    std::binary_semaphore signal{0};
    signal.release(); // Thread-agnostic signal: another thread may acquire()
    signal.acquire();
}
```

## What to remember

- Prefer `std::jthread` over `std::thread` so destructors request cancellation and join cleanly; declare `std::jthread` **last** among class members it touches.
- Pair `std::stop_token` with `std::condition_variable_any` or `std::stop_callback` for race-free cooperative shutdown without polling delays.
- Default to `std::scoped_lock` for simple or multi-mutex locking, reserve `std::unique_lock` for condition variables or deferred/manual unlocking, and always name your lock variable.
- Never call `condition_variable::wait(lk)` without a predicate; spurious and missed wakeups require checking shared state in a loop under the lock.
- Use `std::latch` for one-shot countdowns, `std::barrier` (with a `noexcept` completion callable) for phased work, and `std::binary_semaphore` instead of `std::mutex` when signaling across different threads.

## Concept Map Outline

- **Threads, jthread & locks:** RAII thread lifetimes, cooperative stop tokens, and structured synchronization prevent leaks and races.
  - **Thread ownership (thread vs jthread):** Raw std::thread aborts if unjoined; std::jthread stops and joins automatically.
    - **~thread() calls std::terminate():** Destroying a joinable std::thread aborts rather than silently detaching or deadlocking.
    - **~jthread() stops then joins:** Requests stop on its internal stop_source and joins before leaving scope.
    - **Declare jthread member last:** Reverse member destruction joins the worker before mutexes or state are destroyed.
  - **Cooperative cancellation:** stop_source and stop_token coordinate clean shutdown without async kills.
    - **stop_source & stop_token:** Reference-counted atomic stop state injected automatically into jthread callables.
    - **Synchronous stop_callback:** Runs immediately in its constructor if stop was already requested, preventing missed signals.
    - **condition_variable_any stop wait:** wait(lk, st, pred) registers a stop_callback internally to wake sleeping waiters.
  - **Mutexes & RAII locks:** Scope-bound lock wrappers match single, multi-mutex, and reader-writer patterns.
    - **scoped_lock avoids deadlocks:** Locks multiple mutexes via std::lock without ordering deadlocks.
    - **unique_lock for deferral & CVs:** Movable wrapper supporting defer_lock, early unlock(), and condition variables.
    - **shared_mutex & shared_lock:** Allows concurrent readers under shared_lock and exclusive writers under unique_lock.
    - **Unnamed lock temporary trap:** Omitting a variable name unlocks immediately at the semicolon before the guarded block.
  - **Condition variables:** Predicate waits guard against spurious wakeups and lost notifications.
    - **Always pass a predicate:** cv.wait(lk, pred) loops under the lock so spurious wakeups cannot break invariants.
    - **Unlock before notify:** Releasing the mutex prior to notify prevents woken threads from immediately stalling.
  - **C++20 coordination & call_once:** Latches, barriers, semaphores, and once_flag cover phased and cross-thread signaling.
    - **Single-use std::latch:** Downward counter where threads wait until arrivals reduce the count to zero.
    - **Reusable noexcept std::barrier:** Phased rendezvous mandating a nothrow-invocable completion callable.
    - **Unowned counting_semaphore:** Permits one thread to release() a token acquired by another thread.
    - **Exception-retrying call_once:** If the first callable throws, another waiting thread retries initialization.

## Standardese Quiz Questions

### Question 1 [warmup] ([thread.thread.destr], [thread.jthread.cons])

If do_work() throws an exception after t is launched below, what happens when stack unwinding destroys t?

```cpp
void run() {
    std::thread t([] { /* work */ });
    do_work(); // throws std::runtime_error
    t.join();
}
```

A. ~std::thread() automatically calls t.join() before propagating the exception
B. ~std::thread() automatically detaches t so it runs in the background
C. ~std::thread() calls std::terminate() because t.joinable() is still true
D. Compilation fails because std::thread requires a try/catch block

**Answer (C):** ~std::thread() calls std::terminate() because t.joinable() is still true

**Why:** Because t was neither joined nor detached before unwinding reached ~std::thread(), t.joinable() remains true. Under [thread.thread.destr], destroying a joinable std::thread immediately calls std::terminate(), unlike C++20 std::jthread, which requests stop and joins automatically.

### Question 2 [warmup] ([thread.lock.scoped])

What bug exists in the transfer function below?

```cpp
void transfer(std::mutex& m1, std::mutex& m2) {
    std::scoped_lock(m1, m2);
    // critical section modifying shared state
}
```

A. std::scoped_lock(m1, m2); creates an unnamed temporary that locks and immediately unlocks at the semicolon, leaving the critical section unprotected
B. std::scoped_lock deadlocks when passed two mutexes
C. std::scoped_lock only accepts one mutex in C++23
D. The function leaks both mutexes when returning

**Answer (A):** std::scoped_lock(m1, m2); creates an unnamed temporary that locks and immediately unlocks at the semicolon, leaving the critical section unprotected

**Why:** Because no variable name is given, std::scoped_lock(m1, m2); constructs a temporary object whose lifetime ends at the semicolon, unlocking m1 and m2 right before the critical section executes. Writing std::scoped_lock lk(m1, m2); binds a named guard to the scope.

### Question 3 [tricky] ([class.dtor], [thread.jthread.destr])

Look closely at the member declaration order inside Pipeline. Why is ~Pipeline() unsafe when Pipeline goes out of scope?

```cpp
class Pipeline {
    std::jthread worker_;
    std::mutex mtx_;
    bool active_ = true;
public:
    Pipeline() : worker_([this](std::stop_token st) {
        while (!st.stop_requested()) {
            std::scoped_lock lk(mtx_);
            if (!active_) break;
        }
    }) {}
};
```

A. std::jthread cannot capture this in its constructor lambda
B. std::scoped_lock cannot be constructed inside a while loop
C. ~jthread() does not call request_stop() unless stop_source is passed manually
D. Members are destroyed in reverse declaration order, so mtx_ is destroyed BEFORE ~jthread() requests stop and joins worker_

**Answer (D):** Members are destroyed in reverse declaration order, so mtx_ is destroyed BEFORE ~jthread() requests stop and joins worker_

**Why:** Class data members are always destroyed in reverse order of declaration ([class.dtor]). Because worker_ is declared first, mtx_ and active_ are destroyed first while worker_ is still running its loop—invoking undefined behavior. Declaring std::jthread worker_; last guarantees it stops and joins before mtx_ and active_ die.

### Question 4 [tricky] ([thread.mutex.requirements.mutex], [thread.sema.cnt])

Thread A needs to signal Thread B that a buffer is ready, so Thread B can proceed and unblock. Which synchronization primitive is legal when Thread A unlocks/signals and Thread B acquires?

A. Locking a std::mutex on Thread B and calling m.unlock() from Thread A
B. Calling sem.release() on Thread A and sem.acquire() on Thread B with std::binary_semaphore sem{0}
C. Destroying a std::lock_guard created on Thread A from Thread B
D. Using std::shared_lock on Thread A and unlocking it from Thread B

**Answer (B):** Calling sem.release() on Thread A and sem.acquire() on Thread B with std::binary_semaphore sem{0}

**Why:** std::mutex has strict thread ownership: unlocking a mutex from a thread that does not own the lock is undefined behavior ([thread.mutex.requirements.mutex]). By contrast, std::counting_semaphore and std::binary_semaphore have no thread ownership—any thread may call release() while another calls acquire().

### Question 5 [standardese] ([thread.condition.condvarany])

Why does std::condition_variable_any::wait(lk, st, pred) still check pred() inside a loop, even with a std::stop_token?

A. Only std::condition_variable suffers from spurious wakeups; condition_variable_any never wakes spuriously
B. A stop_token disables mutex locking inside condition_variable_any
C. Condition variable waits may experience spurious wakeups ([thread.condition.condvarany]), so the overload loops until either pred() returns true or st.stop_requested() becomes true
D. wait(lk, st, pred) throws std::system_error when st.stop_requested() is true

**Answer (C):** Condition variable waits may experience spurious wakeups ([thread.condition.condvarany]), so the overload loops until either pred() returns true or st.stop_requested() becomes true

**Why:** Under [thread.condition.condvarany], wait(lock, stoken, pred) repeatedly waits while !stoken.stop_requested() and !pred(), returning pred() once either the predicate holds or stop was requested. This handles both spurious wakeups and stop requests delivered before or during the wait.

### Question 6 [standardese] ([thread.barrier], [thread.once.callonce])

Which statement accurately captures the C++ standard rules for std::barrier's CompletionFunction and std::call_once's callable if exceptions occur?

A. std::barrier catches and ignores exceptions thrown by CompletionFunction, while std::call_once marks the once_flag permanently failed on exception
B. Both std::barrier and std::call_once call std::terminate() if their callables throw
C. Neither std::barrier nor std::call_once constrains exceptions on its callable
D. std::barrier mandates std::is_nothrow_invocable_v<CompletionFunction&> (noexcept), whereas an exception from std::call_once leaves the once_flag uncompleted so another thread retries

**Answer (D):** std::barrier mandates std::is_nothrow_invocable_v<CompletionFunction&> (noexcept), whereas an exception from std::call_once leaves the once_flag uncompleted so another thread retries

**Why:** Under [thread.barrier], std::barrier<CompletionFunction> requires is_nothrow_invocable_v<CompletionFunction&> to be true (a non-noexcept completion callable is ill-formed). Under [thread.once.callonce], an invocation of std::call_once that exits via an exception is classified as an exceptional execution rather than returning, allowing a subsequent waiting invocation to try again.
