04

Chapter 04 — SIGTERM to Clean jthread Shutdown

A process whose SIGTERM path calls request_stop() on every outstanding jthread and joins them all exits cleanly, well inside an orchestrator's grace period.

Demo 04Source on GitHub ↗

The full source for this example lives in examples/concurrency/04-jthread-shutdown/ — clone the repo, cd in, and ./demo.sh.

Chapter reference: Doc 4 — Threads in Modern C++

What it shows

Several jthread workers poll a stop_token in a tight loop while a real SIGTERM handler is installed before any of them start. Because std::stop_source::request_stop() is not guaranteed async-signal-safe, the handler only performs a relaxed atomic store; the main thread polls that flag and performs every request_stop()/join() call itself — a clean shutdown path without smuggling undefined behavior into a signal handler. The verifier drives the binary as its own child process, sends a SIGTERM, and asserts the process exits 0 inside a configurable grace period, escalating to SIGKILL (and a hard failure) only if it doesn’t.

Running it

cd examples/concurrency/04-jthread-shutdown
./demo.sh            # build + run jthread_shutdown + verify.lua
./demo.sh --clean    # remove the image