skip to content

Your C++ codebase launches background work with std::async everywhere; would you ban it in favour of a thread pool, and what would you standardise instead?

level: principalimportance: should knowfreq 30%

answer

  1. no control over thread count
  2. default policy may defer
  3. destructors that wait
  4. restrict, route, measure

basics

~20 s

Usually restrict rather than ban: std::async cannot cap thread count, may defer by default, starts a thread per call in libc++ and libstdc++, and hides waits in destructors. Route frequent work through one owned pool; keep launch::async for rare coarse tasks.

solid answer

~40 s

`std::async` is convenient — a function call that returns a `std::future` and carries exceptions — but at scale its costs show. In libc++ and libstdc++ each `launch::async` call starts a new thread, so many small tasks pay thread start-up and oversubscribe the cores, and `std::launch::async` alone throws `std::system_error` when no thread can be started. The default policy may defer, the futures can block in their destructors, and there is no cancellation, priority or continuation. A workable policy: forbid the policy-free overload, allow `std::async(std::launch::async, ...)` for a handful of long, coarse tasks, and send everything frequent through one shared, sized pool that returns `std::future` via `std::packaged_task`. Watch C++26 `std::execution` as the standard's long-term answer, with partial library support today.

go deeper

for a junior

Know that std::async starts work that may run on a new thread, and that many small tasks are better handed to a pool.

for a middle

Explain the costs: a thread per call in common libraries, possible deferral by default, and futures whose destructors wait.

for a senior

Build or use a pool that returns std::future through packaged_task, size it deliberately, and keep exception propagation intact.

for a principal

Set the rule by measured call volume: restrict std::async to explicit-policy coarse tasks, route the rest through one owned pool, and track std::execution adoption.

## What `std::async` gives and what it withholds | Gives | Withholds | |---|---| | One call to run a function and get a `std::future` | Any limit on how many threads run at once | | Exception transport to `get()` | A guarantee of concurrency under the default policy | | No pool to write or own | Cancellation, priorities, continuations, "wait for any" | | Standard, portable spelling | Control over which thread runs the work | The standard specifies `launch::async` as running the function "as if in a new thread of execution represented by a `thread` object". Both open-source standard libraries take that literally: libc++ starts a detached `std::thread` per call, and libstdc++ starts a thread and joins it when the state is released. ## Costs at scale - **Thread start-up per task.** Fine for a task that runs for seconds; dominant for one that runs for microseconds. - **Oversubscription.** Nothing caps the number of concurrent tasks, so a burst launches more threads than cores, and they compete for CPU and cache. - **Resource exhaustion.** With `std::launch::async` alone, failure to start a thread throws `std::system_error` with `resource_unavailable_try_again`; with the default policy the library may silently defer instead, which hides the problem. - **Hidden waits.** The last future of an unfinished `std::async` task may block in its destructor, so lifetime mistakes turn into serial code or into stalls during unwinding. - **No composition.** The standard `std::future` has no continuation; chaining means blocking a thread in `get()`. - **Per-call `thread_local` state.** In these two libraries each task gets a fresh thread, so per-thread caches are rebuilt every time. ## The options 1. **Leave it.** Reasonable in tools, tests and programs that launch a few coarse tasks. 2. **Restrict it.** Ban the policy-free overload, allow `std::launch::async` for long-running, low-count work, and enforce it in review or with a lint rule. 3. **Replace it with a shared pool.** One sized pool owned by the application, with a `submit` function returning a `std::future`: the pool wraps each job in a `std::packaged_task`, keeps the task behind a `std::shared_ptr` so a copyable `std::function<void()>` can hold it (or stores it in a C++23 `std::move_only_function<void()>`), and runs it on a worker. 4. **Adopt a task library** with work stealing and continuations, accepting a dependency and its learning curve. 5. **Plan for C++26 `std::execution`.** Senders and receivers give the standard a model for describing work and the execution resource it runs on, including a `parallel_scheduler`. It is standardized but not yet broadly implemented — libc++'s status page does not list it as complete — so it is a direction, not today's default. ## A workable policy - No `std::async` without an explicit policy. - `std::launch::deferred` only for genuinely lazy values. - Short or frequent tasks go to the application pool; the pool's size is a deliberate, measured setting. - Every submitted task has an owner that calls `get()`, so exceptions are never dropped. - Code that must cancel uses a stop mechanism the pool understands, not abandoned futures. ## What a migration looks like 1. Inventory the call sites and classify them: one-off coarse tasks, per-request or per-item tasks, and fire-and-forget calls whose futures are dropped. 2. Fix the correctness traps first — explicit policies, futures held until `get()` — because they are bugs whatever the outcome. 3. Introduce the pool behind a small interface such as `submit(callable) -> std::future<R>`, so call sites change one line and keep the same future-based contract and exception propagation. 4. Move the high-volume sites, measure thread counts and latency before and after, and keep the remaining coarse `std::async` calls where they are clearer. 5. Record the rule in the coding standard so new code follows it. ## When `std::async` is the right call A command-line tool that decodes three files in parallel, a test that needs a background producer, or a startup step that loads two large resources concurrently: few tasks, each long, all joined before the function returns. There, a pool would add code and an owner for no measurable benefit, and `std::async(std::launch::async, ...)` with futures held in a container is clear and correct. ## How to decide Measure before banning: count `std::async` call sites, find the hot ones, and look at thread counts under load. If thread creation or oversubscription shows up in profiles, the pool pays for itself. If it does not, the restriction rules above remove the correctness traps without the migration.

  • How does a pool built on std::packaged_task still give callers a std::future?
    `submit` creates a `std::packaged_task` for the job, takes its `get_future()` to return to the caller, and enqueues the task for a worker. Because `std::function<void()>` needs a copyable target, the task is held by a `std::shared_ptr` and the queue stores a lambda that calls it; C++23's `std::move_only_function` removes that indirection.
  • Why not simply cap concurrency by counting outstanding std::async calls?
    A counter limits how many tasks run, but each still starts its own thread, keeps fresh `thread_local` state and may block in its future's destructor. A pool fixes the thread count and reuses threads, which is the cost that matters for many short tasks; a counter only manages the symptom.

  • std::async reuses threads from a standard library pool
  • The default policy guarantees each task its own thread
  • C++26 std::execution can replace std::async in every toolchain today
  • A pool removes the need to call get() on submitted tasks
  • Banning std::async outright is always right regardless of call volume

Assumes C++23 as the current standard: std::move_only_function arrived in C++23, and std::execution with parallel_scheduler is C++26, finished but only partly implemented.