Asynchronous work, cancellation, and shutdown
What you will learn on this page
Section titled “What you will learn on this page”- Why a thread must be joined, never left behind, and why
std::jthreadis the default for threads an object owns. - How a job’s result and exception travel back to the caller
through a
std::future. - How to ask running work to stop with a
std::stop_token, and why C++ cancellation is always cooperative. - Why a class’s member order is its shutdown order.
- The steps of a graceful shutdown, and the choice between finishing queued work and discarding it.
Thread safety was about threads that share data. This page is about threads that hand work to each other: one thread asks for something to be done, another does it, and the first one later wants the answer, or wants it to stop. The hard part is rarely starting the work. It is the end: knowing when it is finished, getting its errors back, stopping it early, and making sure nothing still runs when the objects it uses are destroyed.
The problem
Section titled “The problem”A document service handles requests on a few threads. Some requests need slow work, such as counting the words in a large document or exporting it, and the request thread must not do that work itself:
- W1. A caller hands off a job and gets its result later. If the job throws, the caller gets the exception, not a crash.
- W2. A fixed number of worker threads, chosen at start, run the jobs. Starting a thread per job is too expensive and has no limit.
- W3. A long job can be asked to stop. It stops at the next point where stopping is safe.
- W4. Shutdown has two modes. Finish: run every job already queued, then stop. Discard: drop the queued jobs and ask the running ones to stop. A caller whose job was dropped must find out; it must not wait forever.
- W5. Once shutdown has started, new jobs are refused, and the caller is told.
- W6. No job runs after the pool is destroyed, and no thread outlives the data it uses.
W6 sounds obvious. The first version breaks it anyway.
A first version: a thread nobody waits for
Section titled “A first version: a thread nobody waits for”An autosave feature saves a draft every few milliseconds on a thread of its own. Its first version starts the thread and detaches it, so that nobody has to manage it:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
class Autosaver { // FLAWED: starts a thread that outlives the objectpublic: Autosaver() { // starts the autosave thread, then returns at once std::thread([this] { // [this]: a raw pointer to this object while (!stopping_.load()) { // reads this->stopping_ std::this_thread::sleep_for(10ms); // the object may die meanwhile saves_.fetch_add(1); // "save the draft": writes this->saves_ // Where it goes wrong: nothing ties this thread's life to the // object's. If the object was destroyed during the sleep above // (in main(), unique_ptr then frees its memory), this line // writes into freed memory anyway: a use after free, which is // undefined behavior. The loop test then reads stopping_ from // the same freed memory. // Both members being atomic does not help: atomics stop data // races between living threads; they cannot keep an object // alive. } }).detach(); // nobody will ever wait for this thread // detach() lets the thread run on with no owner, so no code can // ever join it: nothing can wait until it has stopped using `this`. }
// The destructor only sets a flag. It returns at once, and then the // object's memory is freed, while the thread may still be asleep and // about to touch saves_ and stopping_. A correct version would also // wait for the thread to finish (join it) before returning. ~Autosaver() { stopping_.store(true); } // asks, but does not wait
int saves() const { return saves_.load(); }
private: // Shared by the creating thread and the autosave thread, so atomic. std::atomic<bool> stopping_{false}; std::atomic<int> saves_{0};};The thread captures this. The destructor sets stopping_, which the
thread will notice the next time it wakes, but the destructor returns
at once, and the object’s memory is freed while the thread is still
asleep. When it wakes, it writes saves_ and then reads stopping_,
in memory that no longer belongs to any object. That is undefined
behavior.
We ran the flawed program, which destroys the Autosaver after 35
milliseconds and then waits a little longer before it exits. In the
unoptimized gcc-debug build, all three runs printed the expected
lines and exited with status 0: nothing visible went wrong. Under
AddressSanitizer, all three runs reported the same error, shortened
here:
ERROR: AddressSanitizer: heap-use-after-freeWRITE of size 4 at 0x602000000014 thread T1 #1 Autosaver::Autosaver()::'lambda'()::operator()() const detached_autosaver.cpp:19:24freed by thread T0 here: #2 std::unique_ptr<Autosaver>::~unique_ptr()Line 19 is saves_.fetch_add(1): the detached thread (T1) writes to
the object after the main thread (T0) freed it. A silent run is the
worse outcome. The freed memory could have been reused for another
object by then, and the thread would have changed that object instead.
detach() gives up the only way to know when a thread has finished.
After it, nothing can wait for the thread, and the thread may still be
running while objects it uses are destroyed, including, at the end of
the program, global and static objects. The rule this page follows is
short: every thread is joined by the object that owns it, before
the data it uses is destroyed.
Step 1: classify the pieces
Section titled “Step 1: classify the pieces”Before writing the pool, sort out what is data, who owns it, and which thread touches it. The words come from Thread safety and Ownership graphs.
| Piece | What it is | Owner | Touched by |
|---|---|---|---|
| A job | A callable that takes a std::stop_token (a value) |
The queue, then the worker running it | The submitting thread, then one worker |
| A result | The job’s return value or exception | Shared by the job’s task and its future | The worker sets it once; the caller reads it once |
| The queue | Jobs waiting for a worker | The pool | Every submitter and every worker: guarded by a mutex |
| Accepting | Whether new jobs are allowed | The pool | Submitters, workers, shutdown: same mutex as the queue |
| The workers | The threads that run jobs | The pool, as std::jthread members |
Started by the constructor, joined by shutdown |
| The stop signal | “Stop what you are doing”, sent to running jobs | The pool owns the std::stop_source |
shutdown requests it; each job checks its token |
The member functions sort the same way. submit is a command any
thread may call. shutdown is a lifecycle command: it changes what
the pool will do from then on, and may be called once or several
times. queued is a query. run is the private loop each
worker executes. Nothing about the queue or the threads is visible to
callers, which is what lets the pool promise W6.
The tools C++20 gives you
Section titled “The tools C++20 gives you”std::threadstarts a thread. If astd::threadobject is destroyed while it is still joinable, that is, it still represents a thread that has been neither joined nor detached, even one that has already finished, the program callsstd::terminate(). Its owner must calljoin()(wait for it) ordetach()(give it up) first.std::jthreadis a thread that joins itself. Its destructor first asks the thread to stop, then joins it. It also passes the thread function astd::stop_token, if the function takes one.std::stop_sourceandstd::stop_tokencarry one signal, “please stop”. The source requests it once; every token made from that source sees the request. Astd::stop_callbackruns a function when the stop is requested.std::promiseandstd::futureare the two ends of a one-time channel. One thread sets a value or an exception; another waits for it withget().std::packaged_taskwraps a callable so that calling it sets its future, with the return value or with the exception it threw.std::condition_variable_anycan wait with astd::stop_tokenas well as a predicate, and wakes when a stop is requested, without anybody callingnotify.
Cooperative cancellation is the only kind C++ offers. There is no safe way to kill another thread: a thread stopped at an arbitrary instruction could be holding a lock or be halfway through changing an object, and nothing would ever release the lock or finish the change. So one side asks, and the code that is running checks at points where it knows stopping is safe, and stops itself.
The design
Section titled “The design”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The two ways to stop a pool, chosen by whoever calls shutdown().enum class Shutdown { finish_queued, // run every job already queued, then stop discard_queued, // drop queued jobs and ask running ones to stop};
// Thrown by submit() once the pool has stopped accepting jobs. It is a// std::runtime_error (it derives from it), so code that catches that, or// std::exception, also catches this; what() returns the message below.struct PoolClosed : std::runtime_error { PoolClosed() : std::runtime_error("the pool is shut down") {}};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Thread safety: safe. Any thread may call submit(), including a job.// Any thread except a worker may call shutdown(); several may call it at// once. The destructor shuts down with Shutdown::finish_queued.//// Lifetime: every worker is joined before the pool's members are// destroyed, so no job ever runs after the pool is gone. A job, and every// object it captures, must not use anything its submitter may destroy// once the job's future is ready: the job object itself is destroyed on// the worker shortly after its future becomes ready. Reference captures// are fine; captured objects whose destructors touch the submitter's// data are not.class WorkerPool {public: // Starts `threads` worker threads, which wait for jobs at once. explicit WorkerPool(std::size_t threads); // Same as shutdown(Shutdown::finish_queued): runs every queued job, // then joins every worker. ~WorkerPool();
// Not copyable: the pool owns its threads, and threads cannot be shared // between two owners. (No move is generated either.) WorkerPool(const WorkerPool&) = delete; WorkerPool& operator=(const WorkerPool&) = delete;
// Queues a job that is called as job(stop_token). The future gives its // result or rethrows its exception. Throws PoolClosed after shutdown. // `Job` is any callable type, usually a lambda. The return type is // "a future of whatever job(stop_token) returns". template <typename Job> std::future<std::invoke_result_t<Job&, std::stop_token>> submit(Job job);
// Stops accepting jobs, then returns when every worker has finished. void shutdown(Shutdown how);
// How many jobs are waiting, not yet taken by a worker. Already out of // date when it returns, if other threads are submitting or working. [[nodiscard]] std::size_t queued() const;
private: // One queued job, with its type hidden: something to call with the // cancel token. submit() wraps each job in one of these. using Task = std::function<void(std::stop_token)>;
// The loop each worker thread runs: take a job, run it, repeat, until // the queue is empty and shutdown has begun or worker_stop is requested. void run(std::stop_token worker_stop, std::stop_token cancel);
mutable std::mutex mutex_; // mutable: queued() is const and locks it // Workers sleep on it while the queue is empty. _any, because only // that kind can also wake on a std::stop_token. std::condition_variable_any work_or_shutdown_; std::deque<Task> queue_; // guarded by mutex_ bool accepting_ = true; // guarded by mutex_ // A std::stop_source hands out tokens (get_token()) and can later // request a stop that every one of those tokens sees. std::stop_source cancel_jobs_; // shutdown() asks running jobs to stop std::mutex joining_; // one shutdown() joins at a time
// Declared last, so destroyed first: each std::jthread asks its // worker to stop and joins it while the members above still exist. std::vector<std::jthread> workers_;};- The header comment is the contract. It says which threads may
call what, and it states the lifetime promise (W6) and the rules it
puts on callers: a worker must not call
shutdown, and a job, with everything it captures, must not use something that its submitter may destroy once the job’s future is ready. The second rule is subtle:std::packaged_taskmakes the future ready first, and the job object, with its captures, is destroyed on the worker a moment later, possibly after the caller’sget()has returned. workers_is declared last. Members are destroyed in the reverse of the order they are declared, soworkers_is destroyed first. Normally the destructor’sshutdown()has already joined every worker by then. The order is the safety net for the paths where it has not, such as a constructor that throws after starting some workers: eachstd::jthreadthen asks its worker to stop and joins it whilemutex_,queue_, and the condition variable still exist. Starting the threads in the constructor body, not the member initializer list, means every member exists before any worker runs.- Two stop signals, for two different things.
cancel_jobs_means “jobs, stop what you are doing”, andshutdownsends it only in the discard mode. Eachstd::jthreadalso has its own stop token, which means “worker, leave your loop”. The worker loop listens to its own token; the jobs get the other. std::condition_variable_any, notstd::condition_variable, because only the_anyversion can wait with a stop token.
Submitting a job
Section titled “Submitting a job”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
template <typename Job>std::future<std::invoke_result_t<Job&, std::stop_token>> WorkerPool::submit(Job job) { // Result is the type the job returns when called with a stop token, // worked out by the compiler, such as std::size_t or std::string. using Result = std::invoke_result_t<Job&, std::stop_token>; // packaged_task stores the result or the exception for the future. It // cannot be copied, and std::function needs a copyable target, so the // queue holds a shared_ptr to it. // The job is moved into the task, which owns it from here on. auto task = std::make_shared<std::packaged_task<Result(std::stop_token)>>(std::move(job)); // The caller's end of the connection; it becomes ready when the task // has run, or when the task is destroyed without running. std::future<Result> result = task->get_future(); { const std::scoped_lock lock(mutex_); // Checked under the same lock as the push, so a shutdown cannot // slip in between the check and the push. if (!accepting_) { throw PoolClosed(); // the lock is released as the exception leaves } // The lambda captures `task` by value: it holds its own copy of the // shared_ptr, which keeps the packaged_task alive while queued. // Calling it runs (*task)(stop), which calls the job and stores // what it returned, or what it threw, for the future. queue_.emplace_back([task](std::stop_token stop) { (*task)(std::move(stop)); }); } work_or_shutdown_.notify_one(); // one new job: wake one idle worker return result;}How this code works: One job, from submit to its future
Follow one job through the pool, and count who owns its
std::packaged_task.
- Wrap the job.
std::make_sharedbuilds the packaged task on the heap and moves the job into it. The localtaskis the only owner. - Take the future.
get_futureconnectsresultto the task’s shared state. Nothing is in it yet. - Check and queue, under
mutex_. Ifaccepting_is false,submitthrowsPoolClosed. As the exception leaves, the lock is released andresultandtaskare destroyed, so the job never reaches the queue and the caller gets no future. Otherwise the queue gets a lambda holding its own copy of thestd::shared_ptr: the task now has two owners. - Wake a worker and return. After the lock is released,
notify_onewakes one sleeping worker, if any.submitreturnsresult, and the localtaskis destroyed. Usually the lambda (still in the queue, or already taken by a worker) is now the only owner. If a worker was fast enough to run the job and finish its pass beforesubmitreturned, the localtaskwas the last owner, and step 6 happens here, on the submitting thread. - A worker runs it. The worker moves the
std::functionout of the queue (still one owner) and calls it with the cancel token. The packaged task calls the job and stores the value it returned, or the exception it threw, in the shared state;result.get()can now return it. - The last owner goes. At the end of that pass of the worker’s
loop the
std::functionis destroyed, so the lambda and itsstd::shared_ptrgo too, and (unlesssubmitstill holds its local copy) the packaged task is destroyed. Its result stays in the shared state, which the future also owns.
If a discard shutdown takes the job before a worker does, step 6
happens without step 5: the packaged task is destroyed without ever
running, and its future reports std::future_errc::broken_promise.
- The return type is worked out from the job.
std::invoke_result_t<Job&, std::stop_token>is whatever the job returns when it is called with a stop token. A job that returnsstd::size_tgives astd::future<std::size_t>. std::packaged_taskconnects the job to its future. When a worker calls the task, the task calls the job and stores what it returned, or what it threw, in the future’s shared state. The caller gets it fromfuture.get().- The queue holds
std::functions, and they must be copyable.std::packaged_taskcannot be copied, so the queue holds a lambda that owns astd::shared_ptrto the task, and the lambda can be copied. That costs extra allocations per job. accepting_is checked under the same lock as the push. If it were checked first and the job pushed later, a shutdown in between would let a job into a queue that nobody will run (W5).- The notification comes after the lock is released, as in
Thread safety, and
notify_oneis enough: one new job needs one worker.
The worker loop
Section titled “The worker loop”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Starts the workers. This runs in the constructor body, after every// member has been built, so no worker can see a half-made pool.WorkerPool::WorkerPool(std::size_t threads) { // Room for every thread up front, so emplace_back below never has to // allocate: the only step in the loop that can fail is starting a thread. workers_.reserve(threads); for (std::size_t i = 0; i < threads; ++i) { // If starting a thread throws, the workers already started are // destroyed with workers_: each is asked to stop and joined. // The lambda is the thread's body. It captures `this`, to call // run(), and `cancel`, a copy of the pool's cancel token made now // (an init-capture). Because the body takes a std::stop_token as // its first parameter, std::jthread passes in its own token: the // one this jthread's destructor will use to ask the worker to stop. workers_.emplace_back([this, cancel = cancel_jobs_.get_token()](std::stop_token stop) { run(std::move(stop), cancel); }); }}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One worker's whole life: take the oldest job, run it unlocked, repeat.// Returns once the queue is empty and either the pool is shutting down or// worker_stop has been requested. `cancel` is handed to every job it runs.void WorkerPool::run(std::stop_token worker_stop, std::stop_token cancel) { for (;;) { // loops until one of the returns below Task task; // empty; filled from the queue under the lock { // unique_lock, because the wait below unlocks and relocks it. std::unique_lock lock(mutex_); // Sleeps until there is a job or the pool is shutting down, or // until this worker's std::jthread is asked to stop. Returns // false only in the last case, with the condition still false. const bool woken_for_work = work_or_shutdown_.wait( lock, worker_stop, [this] { return !queue_.empty() || !accepting_; }); // Here mutex_ is held again. If the wait returned true, then // there is a job, or accepting_ is false, or both. A queue that // is still not empty is worked through even during a // finish_queued shutdown; only an empty one ends the loop. if (!woken_for_work || queue_.empty()) { return; // asked to stop, or shut down with nothing left } // Take the job out of the queue (move, not copy), so this // worker alone owns it. task = std::move(queue_.front()); queue_.pop_front(); } // mutex_ unlocked here // Runs the job. A job's exception does not escape here: the // packaged_task inside catches it and stores it in the future. task(cancel); // the job runs with no lock held } // `task` is destroyed here, at the end of each pass}How this code works: What a worker does after each wakeup
Each pass of the loop locks mutex_ and calls the wait. The wait first
checks the predicate, “the queue is not empty, or the pool is not
accepting”. If the predicate is true, the wait returns true at once.
If it is false, the wait releases mutex_ and sleeps, as one step,
until a notification, a stop request on worker_stop, or a spurious
wakeup; then it locks mutex_ again and checks once more. Once a stop
has been requested, it stops sleeping and returns whatever the
predicate says.
What the worker then does depends on the state it sees, with mutex_
held:
queue_ |
accepting_ |
worker_stop requested? |
The wait returns | Then the worker |
|---|---|---|---|---|
| empty | true | no | (keeps sleeping) | does nothing yet |
| not empty | true | no | true |
takes the oldest job, runs it |
| not empty | false | no | true |
takes the oldest job, runs it |
| empty | false | no | true |
returns: the pool shut down |
| empty | true | yes | false |
returns |
The third row is the finish mode at work: the pool has stopped
accepting, but the worker keeps taking jobs until the queue is empty.
The last row happens only when workers_ is destroyed without a
shutdown first. In every row where the worker takes a job, it moves
the job out and pops the queue while it still holds the lock, unlocks,
and only then runs the job.
- The wait has a predicate and a stop token. It returns when there
is a job or the pool is shutting down. It also returns if this
worker’s
std::jthreadis asked to stop, which happens only whenworkers_is destroyed without ashutdownfirst: for example, if starting the third thread throws in the constructor, and the first two are destroyed with the half-built pool. - “Shutting down and the queue is empty” ends the loop. In the
finish mode,
accepting_is false but the queue still holds jobs, so each worker keeps taking jobs until the queue is empty, and only then returns. That is what makes the finish mode finish (W4). - The job runs with no lock held. A job is unknown code, it may be
slow, and it may call
submit, which takes the same mutex. Under the lock, the first two would hold up every other worker, and the third would lock astd::mutexthe thread already holds, which is undefined behavior and in practice usually a deadlock. - The job gets the pool’s cancel token, copied into each worker
when it was started, so the workers never touch the
std::stop_sourceitself whileshutdownuses it.
Shutting down
Section titled “Shutting down”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Stops the pool in five numbered steps (below), and returns only when// every worker has finished. Safe to call more than once and from several// threads at once, but never from a job: a worker cannot join itself.void WorkerPool::shutdown(Shutdown how) { // Receives the dropped jobs, so they can be destroyed outside the lock. std::deque<Task> discarded; { const std::scoped_lock lock(mutex_); accepting_ = false; // 1. no new jobs from now on if (how == Shutdown::discard_queued) { // swap exchanges the two deques' contents: `discarded` gets // every queued job, and queue_ is left empty. No job is copied. discarded.swap(queue_); // 2a. take the queued jobs out } } if (how == Shutdown::discard_queued) { // Every job's `cancel` token now reports stop_requested() == true. // A job sees it only when it next checks; nothing is interrupted. cancel_jobs_.request_stop(); // 2b. ask running jobs to stop } // Sleeping workers recheck their condition: accepting_ is now false, // so each takes a remaining job or, if none is left, returns. work_or_shutdown_.notify_all(); // 3. wake every idle worker
// 4. Destroy the dropped jobs now, with no lock held and before the // joins. Each dropped packaged_task makes its future throw // std::future_error (broken_promise) at once, so no caller, not even a // running job, waits for a job that will never run. discarded.clear();
// Only one caller joins at a time. A second caller waits here, then // finds every worker already joined (not joinable) and skips them. // Held until shutdown returns. const std::scoped_lock lock(joining_); for (std::jthread& worker : workers_) { // joinable() is false for a thread that was already joined. if (worker.joinable()) { worker.join(); // 5. wait for each worker to run out of work and return } }}Text description of the diagram
The caller calls shutdown with the discard mode. Under the pool’s
lock, the pool sets accepting_ to false, so no new job is accepted,
and moves the queued jobs out into a local container. It then requests
a stop through the cancel token that every running job received,
and wakes every worker. Next it destroys the jobs it took out; each
one was never run, so its future now reports a broken promise. Only
then does it start joining the workers. The running job sees the stop
request the next time it checks, returns, and its worker goes back to
the queue. The queue is empty and the pool is no longer accepting, so
the worker leaves its loop, its thread finishes, and the join returns.
Then shutdown returns to the caller. In the finish mode, the pool
skips taking the queue, requesting the stop, and destroying jobs, and the workers keep running
queued jobs until the queue is empty before they leave their loops.
Diagram source (Mermaid)
sequenceDiagram
participant C as Caller
participant P as WorkerPool
participant W as Worker
participant J as Running job
C->>P: shutdown(discard_queued)
P->>P: under the lock, accepting = false, take the queued jobs
P->>J: request stop through the cancel token
P->>W: notify all workers
P->>P: destroy the taken jobs, their futures report broken promise
P->>W: join
J->>J: sees the stop request at its next check
J-->>W: returns its result
W->>W: queue empty and not accepting, so leave the loop
W-->>P: thread finished, join returns
P-->>C: shutdown returns- The order of the steps is the design. New jobs are refused first, so the work can only shrink. Then the queue is taken or left, the running jobs are asked to stop, the workers are woken, and the taken jobs are destroyed. Only then does the pool wait. Waiting before waking would wait forever for idle workers that are asleep.
- Discarded jobs are not silently lost. Destroying a
std::packaged_taskthat never ran stores astd::future_errorwith the codestd::future_errc::broken_promisein its future, so a caller waiting inget()wakes up with an exception (W4). - They are destroyed with no lock held, and before the joins.
Destroying a job runs the destructors of whatever it captured, which
is unknown code, and wakes any thread waiting on its future. Neither
should happen under
mutex_. Doing it before the joins matters too: a running job that waits on the future of a job the discard dropped would otherwise wait for a broken promise that comes only after the join, while the join waits for that job. An earlier version of this pool destroyed them after the joins, and our review found that it hung in exactly that case. joining_lets several threads callshutdown. Callingjoinon the samestd::jthreadfrom two threads at once is a data race. With the second mutex, the second caller waits until the first has joined every worker, then finds none joinable and returns. Both return only when the pool has stopped.joining_is never held together withmutex_, so there is no lock order to keep.- A job must not call
shutdown. Its worker would try to join itself.std::thread::joinreports that with astd::system_error, which in this pool comes out of that job’s future, but a job callingshutdownwhile another thread also calls it could instead wait forever, so the contract forbids it. - The destructor finishes the queue.
~WorkerPoolcallsshutdown(Shutdown::finish_queued), so a pool that goes out of scope never drops work it accepted. A caller who wants the faster mode calls it first. A second call does nothing harmful: the pool is already closed and every worker already joined.
Running it
Section titled “Running it”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
int main() { // 1. Results and exceptions come back through futures. The pool's // destructor runs every queued job, then joins its workers. // Declared outside the block, so the futures outlive the pool and can // be read after it is gone. std::vector<std::future<std::size_t>> counts; { work::WorkerPool pool(2); for (const std::string text : {"to be or not to be", "", "all done"}) { // [text] captures a copy of the string, so the job owns its // text and does not depend on the loop variable, which may be // gone before a worker runs the job. count_words("") throws. counts.push_back(pool.submit([text](std::stop_token) { return count_words(text); })); } } // every job has finished here for (std::size_t i = 0; i < counts.size(); ++i) { try { // get() waits if needed (here every job is done), then returns // the result, or rethrows the exception the job threw. const std::size_t words = counts[i].get(); // rethrows the job's exception std::cout << "document " << i + 1 << ": " << words << " words\n"; } catch (const std::invalid_argument& error) { std::cout << "document " << i + 1 << ": failed, " << error.what() << '\n'; } }
// 2. Shutting down without waiting for the queue. // A promise<void> carries no value, just "it happened": set_value() // makes its future ready, and a wait() on that future returns. std::promise<void> export_started; // declared before the pool: outlives every job work::WorkerPool pool(1); // A long export that checks its stop token between chunks. The token is // the pool's cancel token, requested only by a discard shutdown. auto exported = pool.submit([&export_started](std::stop_token stop) { export_started.set_value(); // "the export is running now" while (!stop.stop_requested()) { std::this_thread::sleep_for(1ms); // one chunk of a long export } return std::string("export stopped between chunks"); }); export_started.get_future().wait(); // the one worker is now busy std::vector<std::future<std::string>> reports; reports.push_back(pool.submit([](std::stop_token) { return std::string("report A"); })); reports.push_back(pool.submit([](std::stop_token) { return std::string("report B"); })); std::cout << "jobs queued behind the export: " << pool.queued() << '\n';
// Drops both reports, asks the export to stop, and returns once the // export has seen the request, returned, and its worker has been joined. pool.shutdown(work::Shutdown::discard_queued); std::cout << exported.get() << '\n'; for (auto& report : reports) { try { std::cout << report.get() << '\n'; } catch (const std::future_error& error) { // A job destroyed without running leaves its future with this // error code. const bool dropped = error.code() == std::future_errc::broken_promise; std::cout << (dropped ? "a queued report was dropped" : "unexpected error") << '\n'; } } // After shutdown, submit() throws instead of queuing a job nobody runs. try { static_cast<void>(pool.submit([](std::stop_token) { return 0; })); } catch (const work::PoolClosed& error) { std::cout << "new job refused: " << error.what() << '\n'; }} // Locals die in reverse order: `pool` (whose second shutdown finds // nothing left to do) goes before export_started, declared earlier.document 1: 6 wordsdocument 2: failed, nothing to countdocument 3: 2 wordsjobs queued behind the export: 2export stopped between chunksa queued report was droppeda queued report was droppednew job refused: the pool is shut downHow this code works: The discard demo, step by step
The second half of main uses a pool with one worker. These are the
steps behind the last five lines of the output.
| Step | Main thread | The one worker | queue_ |
accepting_ |
|---|---|---|---|---|
| 1 | builds pool(1) |
starts; sleeps while there is no job | empty | true |
| 2 | submits the export, notifies | wakes, takes the export, runs it | empty | true |
| 3 | waits on export_started |
export calls set_value, then loops |
empty | true |
| 4 | wait returns; submits report A and report B | still inside the export | A, B | true |
| 5 | prints jobs queued behind the export: 2 |
still inside the export | A, B | true |
| 6 | shutdown: sets the flag, swaps the queue out |
still inside the export | empty | false |
| 7 | requests the cancel stop, notifies, drops A and B | export sees the stop, returns its text | empty | false |
| 8 | joins the worker, waiting | wait returns, queue empty: returns | empty | false |
| 9 | join returns; shutdown returns |
(finished) | empty | false |
Steps 7 and 8 overlap: the export may see the stop request before or
after the two reports are destroyed. Either way, join returns only
once the export has returned. Then:
exported.get()returns the export’s text, andmainprintsexport stopped between chunks.- Each report’s packaged task was destroyed without running, so each
get()throwsstd::future_errorwith the codebroken_promise:a queued report was dropped, twice. - The last
submitfindsaccepting_false and throwsPoolClosed:new job refused: the pool is shut down. - At the closing brace,
~WorkerPoolcallsshutdownagain. The flag is already false, the queue is empty, and the worker is no longer joinable, so it has nothing left to do.
The notifications from the two report submit calls in step 4 wake
nobody: the only worker is busy running the export, not waiting.
- Results come back in submission order because the program reads the futures in that order. The two workers may have run the jobs in any order; the output does not depend on it.
- The empty document’s exception came back through its future.
The program calls
get()before it prints anything about that document. Our first version wrote"document 2: "and only then calledget(), so the output stream already held half a line when the exception was thrown, and the line came out asdocument 2: document 2: failed. - The first pool is destroyed at the closing brace, and its destructor finishes the queue. By the time the futures are read, every job has run.
export_startedis declared before the second pool. The export job refers to it, so it must outlive every job: declared first, it is destroyed after the pool, which joins its worker first. This is W6 again, written as declaration order inmain.- The two reports are queued, not running, because the program
waits until the export has started on the only worker. Without that
wait, the export might still be queued:
queued()could print 3, and the discard would drop the export too, soexported.get()would throw. - The export stops between chunks after the discard. Its loop is a stand-in for real work in steps, checking the token between steps.
Testing
Section titled “Testing”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one// if the two values are not equal, and prints both; and// LLD_CHECK_THROWS(expression, type) fails unless the expression throws// that type. They come from the site's small test header, lld_test.hpp,// and must run on the main thread.
// Queues 100 jobs on two workers, then shuts down in the finish mode.// Proves that shutdown returns only after all 100 have run.LLD_TEST(finish_queued_runs_every_job_already_queued) { std::atomic<int> ran{0}; // atomic: both workers add to it WorkerPool pool(2); for (int i = 0; i < 100; ++i) { // An unnamed std::stop_token parameter: the job accepts the token // but never checks it. static_cast<void> says the returned future // is ignored on purpose. static_cast<void>(pool.submit([&ran](std::stop_token) { ran.fetch_add(1); })); } pool.shutdown(Shutdown::finish_queued); LLD_CHECK_EQ(ran.load(), 100); LLD_CHECK_EQ(pool.queued(), 0u);}
// One worker is kept busy by a job that runs until it is asked to stop, so// five more jobs certainly wait in the queue. Proves that the discard mode// stops the running job, runs none of the five, and breaks their futures.LLD_TEST(discard_queued_stops_the_running_job_and_breaks_queued_futures) { // A one-time gate: wait() blocks until count_down() brings 1 to 0. std::latch started{1}; std::atomic<int> queued_ran{0}; WorkerPool pool(1); auto running = pool.submit([&started](std::stop_token stop) { started.count_down(); // "I am running", to the main thread // `stop` is the pool's cancel token: only a discard shutdown // requests it. while (!stop.stop_requested()) { std::this_thread::sleep_for(1ms); } return true; }); started.wait(); // the only worker is busy, so the next jobs stay queued std::vector<std::future<void>> queued; for (int i = 0; i < 5; ++i) { queued.push_back(pool.submit([&queued_ran](std::stop_token) { queued_ran.fetch_add(1); })); } LLD_CHECK_EQ(pool.queued(), 5u);
pool.shutdown(Shutdown::discard_queued); static_cast<void>(running.get()); // it returned, so shutdown could finish LLD_CHECK_EQ(queued_ran.load(), 0); // Each dropped job's packaged_task was destroyed without running, so // its future holds a std::future_error (broken_promise), which get() // throws. for (auto& future : queued) { LLD_CHECK_THROWS(future.get(), std::future_error); }}
// A running job waits on the future of a job that is still queued, then// the queue is discarded. Proves the running job gets a broken promise// instead of waiting forever, so shutdown can join it and return.LLD_TEST(a_running_job_waiting_for_a_dropped_job_is_not_left_waiting) { std::latch started{1}; // A promise is the sending end of a future. This one will carry, // later, the future of the job that is about to be dropped. std::promise<std::future<int>> hand_over; WorkerPool pool(1); // The init-capture moves the receiving end into the job. `mutable`, // because future.get() changes the captured future. auto waiter = pool.submit([&started, future = hand_over.get_future()](std::stop_token) mutable { started.count_down(); std::future<int> dropped = future.get(); // waits until main hands it over try { static_cast<void>(dropped.get()); // waits for a job that never runs return false; // only if the dropped job somehow ran } catch (const std::future_error&) { return true; // the dropped job's promise was broken } }); started.wait(); // the waiter is running, so the next job stays queued // Queues a job (it cannot run: the only worker is busy) and passes its // future to the waiter. hand_over.set_value(pool.submit([](std::stop_token) { return 1; })); pool.shutdown(Shutdown::discard_queued); // would hang if dropped jobs outlived the joins LLD_CHECK(waiter.get());}
// Proves a pool that has shut down refuses new jobs with PoolClosed.LLD_TEST(submit_after_shutdown_throws_pool_closed) { WorkerPool pool(1); pool.shutdown(Shutdown::finish_queued); LLD_CHECK_THROWS(static_cast<void>(pool.submit([](std::stop_token) { return 1; })), work::PoolClosed);}- The finish mode runs every one of 100 queued jobs before
shutdownreturns, and leaves the queue empty. - The discard mode is tested with one worker held busy by a job
that waits for its stop token, so the next five jobs are certainly
queued.
shutdownreturns, which it can do only after the running job has seen the stop and returned; none of the five ran, and every one of their futures throwsstd::future_error. - A running job that waits for a dropped job gets a broken promise instead of waiting forever. The test hands a running job the future of a job that is still queued, then discards the queue. With the dropped jobs destroyed after the joins, this test would hang until the 120-second test timeout failed it.
- A refused job throws
PoolClosed, and the test checks the type.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Four threads submit 500 jobs each while two other threads shut the pool// down. Checks that every submit was either accepted or refused, and that// every accepted job ran: the finish mode loses nothing it accepted.LLD_TEST(many_threads_submit_while_two_threads_shut_down) { std::atomic<int> ran{0}; std::atomic<int> refused{0}; std::atomic<int> accepted{0}; { WorkerPool pool(3); // A starting gate for six threads: arrive_and_wait() counts this // thread in and blocks until all six have arrived, so they start // together. std::latch go{6}; std::vector<std::jthread> threads; for (int t = 0; t < 4; ++t) { threads.emplace_back([&] { go.arrive_and_wait(); for (int i = 0; i < 500; ++i) { try { static_cast<void>(pool.submit([&ran](std::stop_token) { ran.fetch_add(1); })); accepted.fetch_add(1); } catch (const work::PoolClosed&) { // a shutdown got there first refused.fetch_add(1); } } }); } for (int t = 0; t < 2; ++t) { threads.emplace_back([&] { go.arrive_and_wait(); // Two shutdowns at once: joining_ makes the second wait for // the first, then return. pool.shutdown(Shutdown::finish_queued); }); } } // the threads are joined first, then the pool // (`threads` was declared after `pool`, so it is destroyed first.) LLD_CHECK_EQ(accepted.load() + refused.load(), 2000); LLD_CHECK_EQ(ran.load(), accepted.load()); // every accepted job ran}
// A job submits a follow-up job and returns its future, without waiting.// Proves submit() may be called from inside a job, and the follow-up runs.LLD_TEST(a_job_can_queue_a_follow_up_without_waiting_for_it) { WorkerPool pool(1); // `outer` is a std::future<std::future<int>>: the outer job's result is // the follow-up's future. auto outer = pool.submit([&pool](std::stop_token) { // With one worker, waiting here for the follow-up would wait // forever: the follow-up needs the worker this job is using. return pool.submit([](std::stop_token) { return 42; }); }); std::future<int> follow_up = outer.get(); // the outer job has finished LLD_CHECK_EQ(follow_up.get(), 42); // the worker is free, so the follow-up runs}- Four threads submit while two threads shut down. A
std::latchreleases all six at once. Some jobs are accepted and some refused, in proportions that change from run to run, so the test checks only what must always hold: every job was either accepted or refused, and every accepted job ran, because the destructor of a pool shut down in the finish mode loses nothing. - A job can queue a follow-up and return its future. It must not wait for it: with one worker, the follow-up could never start, because the job waiting for it holds the only worker. That is a deadlock without any mutex, sometimes called pool starvation.
- All of these run under the
tsanpreset as well, and ThreadSanitizer reports nothing for them. Every test in the examples also has a 120-second CTest timeout, so a shutdown that never finishes fails the test instead of hanging the run.
What these tests cannot show is that every interleaving of submit and
shutdown is handled. The concurrent test makes some interleavings
likely; the argument that the rest are handled is the one above: one
lock covers accepting_ and the queue, so every submit happens
entirely before or entirely after the moment the pool closes.
The design at a glance
Section titled “The design at a glance”class work::WorkerPool
safe; any thread may submit, any non-worker thread may shut down
Data members
void run(std::stop_token worker_stop, std::stop_token cancel);one worker's loopmutable std::mutex mutex_;std::condition_variable_any work_or_shutdown_;std::deque<Task> queue_;guarded by mutex_bool accepting_;guarded by mutex_std::stop_source cancel_jobs_;stop request for running jobsstd::mutex joining_;one shutdown joins at a timestd::vector<std::jthread> workers_;last member: joined first
Member functions
explicit WorkerPool(std::size_t threads);~WorkerPool();shutdown(Shutdown::finish_queued)std::future<R> submit(Job job);job(std::stop_token) returns R; throws PoolClosed after shutdownvoid shutdown(Shutdown how);refuse, then finish or discard, then join every workerstd::size_t queued() const;
class work::Shutdown
enum class
Member functions
finish_queueddiscard_queued
class work::PoolClosed
exception, derives from std::runtime_error
Member functions
PoolClosed();
When this design fits, and when it does not
Section titled “When this design fits, and when it does not”A fixed pool with futures and cooperative cancellation fits when:
- Many short, independent jobs arrive from several threads, and the number of threads must stay fixed (W2).
- Callers want results or errors back, one per job.
- Shutdown must be predictable: either everything accepted runs, or the caller learns which jobs never will.
Something else fits better when:
- There is one long-lived background task, such as the autosaver.
Give its owner a
std::jthreadmember, declared last, whose loop checks its stop token; a pool adds nothing. - There is one job, once.
std::async(std::launch::async, job)returns a future directly. Its future is unusual: its destructor waits for the job to finish, so a discarded future makes the call block. - Jobs depend on each other, one waiting for another’s result. Waiting inside a job ties up a worker and can starve the pool. Pass futures along, or chain the next job from the end of the first, or use a library designed for task graphs.
- The queue must not grow without limit, which this one does. The page on backpressure and bounded queues is about exactly that.
Common mistakes
Section titled “Common mistakes”- Detaching a thread that uses an object, a reference, or a global. Join it in the destructor of whatever owns it.
- Destroying a joinable
std::thread, which callsstd::terminate(). Preferstd::jthread, or join on every path, including when an exception is thrown. - Declaring the thread member before the data it uses. It starts too early and is joined too late. Declare it last, and say why.
- Waiting for workers before waking them, or setting the shutdown flag without the mutex the workers wait with. A worker can then check the flag, miss the change, and sleep through the only notification.
- Treating a stop request as a kill. Nothing stops until the running code checks its token. A job that never checks makes shutdown wait for it to finish on its own.
- Dropping queued jobs without telling their callers. A caller waiting on a future for a job that will never run waits forever, unless the job’s promise or task is destroyed so that the future reports a broken promise.
- Waiting inside a job for another job in the same pool. With all workers waiting, nothing runs the jobs they wait for.
- Letting an exception escape a thread function. It ends the
program. Catch it in the thread, or let a
std::packaged_taskcarry it to a future.
When the requirements change
Section titled “When the requirements change”- “A job can have a deadline.” Give each job its own
std::stop_source, combined with the pool’s: the job checks both tokens, or astd::stop_callbackon the pool’s token requests a stop on the job’s source. A separate timer thread requests the job’s stop when the deadline passes. The job still decides where it can stop. - “Urgent jobs go first.” The
std::dequebecomes a priority queue, still under the same mutex. Decide what happens to old, low-priority jobs, or they may never run. - “Show progress for long jobs.” The job reports progress through
an object the caller owns and the job only writes to, such as one
std::atomicvalue. The caller must keep that object alive until the job’s future is ready, the rule in the pool’s contract. - “The service must stop within five seconds.” Shut down in the
finish mode, and if the workers have not stopped in time, request
the stop as well. That needs a
shutdownthat waits with a time limit; joining a thread has no timeout, so the workers must signal that they are done, for example by decrementing a counter under the mutex and notifying a condition variable thatshutdownwaits on withwait_for. (std::latchhas no timed wait.) If the time runs out, request the stop, then still join: a thread cannot be left running. - “Stop the whole service in order.” Shut down in the reverse of the order things were started: first stop accepting requests at the edge, then shut down the pool, then flush and close what the jobs used, such as files and connections. If each is an object that owns the next, declared in the order they depend on each other, their destructors do this by themselves.
Exercise
Section titled “Exercise”Exercise: Fix a shutdown race
An uploader sends files on a background thread:
// What it is meant to do: upload() queues a file name for sending; one// background thread sends the queued files, oldest first.// Whether it really does that is the exercise.class Uploader {public: // Starts the background thread at once. The lambda captures `this`, // so the thread can call run() on this object. Uploader() : worker_([this] { run(); }) {}
// Meant to stop the thread: set the flag, wake the thread, and wait // in join() until run() has returned. ~Uploader() { stopping_ = true; wake_.notify_one(); worker_.join(); }
// Any thread may call this. Adds the name to the queue under the // lock, then, after unlocking, wakes the background thread. void upload(std::string file) { { const std::scoped_lock lock(mutex_); files_.push_back(std::move(file)); } wake_.notify_one(); }
private: // The background thread's body. It locks mutex_ once, at the start; // wait() unlocks it while sleeping and locks it again on waking. void run() { std::unique_lock lock(mutex_); while (!stopping_) { wake_.wait(lock); // sleep until notified (no condition given) // Send everything queued, oldest first: send() the front name, // then remove it. while (!files_.empty()) { send(files_.front()); files_.pop_front(); } } }
std::thread worker_; // the background thread, started by the constructor std::mutex mutex_; // upload() and run() lock it around files_ std::condition_variable wake_; // upload() and the destructor notify it std::deque<std::string> files_; // names waiting to be sent bool stopping_ = false; // set by the destructor, read by run()};This class, with the needed includes, a send that prints the file
name, and a main that uploads three files, was compiled with
GCC 11.4; the results of running it are given in the answer. The requirement is that destroying an Uploader sends every
file already passed to upload, then stops.
- A program makes an
Uploader, uploads three files, and lets it go out of scope. Without running it, list everything that can go wrong and why. - Rewrite the class to meet the requirement, using
std::jthread.
Show the explained answer
1. Five problems, from the first line of the constructor to the last line of the destructor:
worker_is declared first, so the thread starts beforemutex_,wake_,files_, andstopping_are constructed. The thread may lock a mutex that does not exist yet.stopping_is written without the mutex while the worker reads it: a data race. It also allows a lost wakeup: the destructor can set the flag and notify between the worker’s check ofstopping_and itswait, and the worker then sleeps forever, sojoinnever returns.- The
waithas no predicate. A file uploaded before the worker first waits sends a notification nobody hears, and then the worker sleeps although there is work, until the next notification. - Files queued at shutdown are dropped. If the worker checks
stopping_after the destructor set it, the loop ends, and any files in the queue are never sent. sendruns under the lock, so everyuploadwaits while a file is sent.- An exception ends the program. If
sendthrows, the exception leaves the thread function, which callsstd::terminate. And if a member declared afterworker_throws while it is constructed (the default constructor ofstd::dequemay allocate, and so throw, in some standard libraries), the already startedstd::threadis destroyed while joinable, which also callsstd::terminate.
When we compiled this class with GCC 11.4 and ran the three-file
program by hand 200 times, every run printed nothing and exited
normally: the main thread uploaded the files and set stopping_
before the worker first checked it, so the worker never sent
anything. In other runs and on other machines the timing differs: when
our review ran it again, a few runs out of 200 sent all three files.
The bugs show up only some of the time, which is what makes them
dangerous. Under ThreadSanitizer, each of three runs reported two data
races, both at the start: the worker locked mutex_ while the
constructor was still initializing it, and read stopping_ before its
initializer had run.
2.
// Thread safety: safe. Any thread may call upload(). The destructor sends// every file already queued, then joins the worker.class Uploader {public: void upload(std::string file) { { const std::scoped_lock lock(mutex_); files_.push_back(std::move(file)); } wake_.notify_one(); }
private: // The background thread's body. `stop` is the jthread's own token: the // jthread destructor requests it. Each pass takes one file out under // the lock and sends it with the lock released. void run(std::stop_token stop) { for (;;) { std::string file; // the file this pass sends, owned by this thread { // unique_lock, because the wait unlocks and relocks it. std::unique_lock lock(mutex_); // Returns at once if a file is queued. Otherwise sleeps, with // mutex_ released, until a file is queued or a stop is // requested, rechecking the condition after every wakeup, // spurious ones included. Returns true if there is a // file, even after a stop request; false only if a stop was // requested and the queue is empty. if (!wake_.wait(lock, stop, [this] { return !files_.empty(); })) { return; // asked to stop, and nothing is left to send } // Move the name out of the queue, then drop the moved-from // entry. The lock is still held for both steps. file = std::move(files_.front()); files_.pop_front(); } // mutex_ unlocked here send(file); // no lock held while sending } }
std::mutex mutex_; // guards files_ // The _any version, because only it can wait with a stop token. std::condition_variable_any wake_; std::deque<std::string> files_; // guarded by mutex_ // Last: started after everything it uses, and joined before they go. // Its lambda takes a std::stop_token, so jthread passes in its own. std::jthread worker_{[this](std::stop_token stop) { run(std::move(stop)); }};};This class, with a send that prints the file name and the same
three-file main, was compiled with GCC 11.4 and Clang 14 and run 200
times with each; every run sent all three files in order. Thirty runs
under ThreadSanitizer reported nothing.
worker_is last, so it starts after everything it uses exists, and, being destroyed first, it is joined while they still exist.- There is no destructor to write. The
std::jthreaddestructor requests a stop and joins. The stop request wakes thewaitthrough the token; nobody has to set a flag or notify. - The wait has a predicate and a token. It returns
truewhile there are files, even after a stop was requested, so the worker sends everything queued. It returnsfalseonly once a stop was requested and the queue is empty: that is the requirement. - The stop flag is gone. The token’s state is the flag, and the standard library makes reading and requesting it safe from any thread.
sendruns with no lock held.
Summary
Section titled “Summary”- Join every thread, in the object that owns it, before the data it uses is destroyed. Do not detach.
- Prefer
std::jthread: its destructor requests a stop and joins. Declare it last, so it starts after and is joined before everything it uses. - A job’s result or exception travels back through a
std::future; astd::packaged_taskfills it in. - Cancellation is cooperative: a
std::stop_tokenasks, and the running code checks at safe points. A blocked job needs astd::stop_callbackor a timeout. - A graceful shutdown refuses new work, finishes or discards the queue, wakes the workers, and then waits. Dropped jobs must break their futures, so no caller waits forever.
- Never wait inside a job for another job in the same pool.