std::execution::spawn_future
| Defined in header <execution>
|
||
inline constexpr /* unspecified */ spawn_future{};
|
(since C++26) (customization point object) |
|
| Call signatures |
||
execution::sender auto spawn_future( execution::sender auto sndr,
execution::scope_token auto token );
|
(1) | (since C++26) |
execution::sender auto spawn_future( execution::sender auto sndr,
execution::scope_token auto token,
/*queryable-object*/ auto env );
|
(2) | (since C++26) |
Starts a sender in the background and returns a sender for its result. spawn_future(sndr, token) tries to associate sndr with the async scope that token refers to and, if that succeeds, starts sndr right away. The returned sender, the future, completes with whatever sndr completes with, once it has completed; if the scope did not accept the work, the future completes with the stopped signal.
This is spawn for work whose result you want. spawn returns void and so only accepts senders that produce nothing and cannot fail. spawn_future accepts any sender, including ones with values and errors, and hands the result back later, so work can be started early and its result collected when it is needed, while the scope still keeps track of the work so the program can wait for it before destroying the resources it uses.
Parameters
| sndr | - | the sender to start; it may complete in any way |
| token | - | a scope token (for example the one from counting_scope) that decides whether the work is accepted into its scope and keeps track of it while it runs |
| env | - | an optional queryable object that is joined into the environment the work sees (for example to choose an allocator); the default is an empty environment. A stop token in env is honored: stop requests from it are passed on to the work
|
Return value
A sender, the future, that when connected and started waits for the spawned work and completes with its result:
- Its completions are those of
sndr, plus the stopped signal, and the result values are copied or moved out of the spawned work. - If the scope accepted the work, the future completes with the same value, error or stopped completion as
sndr. - If the scope did not accept the work (for example, it is closed),
sndris not started and the future completes with the stopped signal. Alternatively, the token may throw an exception, which propagates out ofspawn_future.
spawn_future(sndr, token) is ill-formed if sndr does not satisfy execution::sender, token does not satisfy execution::scope_token, or env is not a queryable object.
Customization point objects
The name execution::spawn_future denotes a customization point object, which is a const function object of a literal semiregular class type. See CustomizationPointObject for details.
Details
- The work starts eagerly, on the calling thread, as part of the call, before the future is connected or started. This differs from most sender algorithms, which do nothing until started.
- The operation state of the work is allocated dynamically, with the allocator from
envif it has one, otherwise the allocator from the environment of the wrapped sendertoken.wrap(sndr)if that has one, otherwise withstd::allocator<void>. It also holds storage for the result, so it is larger than the onespawnallocates. - The work is given a stop token that receives stop requests sent by the future and any stop request that arrives through
get_stop_token(env). - The future cannot be copied, so it is connected and started at most once; the result is moved out of the work to the receiver it is connected to.
Abandoning the work
If the future is destroyed without being started, or the future's operation state is destroyed without being started, the work is abandoned: it is asked to stop, any result it produces is discarded, and its resources are cleaned up when it finishes. If the work is already running, it sees the stop request through its stop token; if it has not started yet, it does not run.
If the future is started and then receives a stop request from its receiver before the work has completed, an attempt is made to abandon the work, and the future then completes with the stopped signal, or with the result if it became available in the meantime, without waiting for the work to finish.
Notes
- The scope counts the work until it has completed and the future has been consumed or abandoned. This has a consequence that is easy to trip over:
joinon a counting_scope does not complete while a spawned future exists that has neither been used nor abandoned, even if the work itself finished. Consume or destroy the futures first, or wait for them together with the scope, for example with when_all. spawn_futurecovers whatensure_starteddid in earlier drafts, with the difference that the scope takes part in the work's lifetime, so the program can wait for the work to finish before destroying anything it uses.- To start work you do not need the result of, use spawn. To tie a sender to a scope without starting it, use associate.
- Unlike
spawn,spawn_futureputs no restriction on the sender: the result can be consumed, so nothing is dropped silently, and errors reach whoever consumes the future.
Example
A computation is started on a worker thread while the program does something else, and its result is collected later. The future is consumed before the scope is joined: join would not complete while a spawned future that is still unused exists.
The standard header is not available in the online compilers yet, so this link runs the example on Compiler Explorer with stdexec, the reference implementation.
#include <chrono>
#include <execution>
#include <print>
#include <thread>
namespace ex = std::execution;
// An event loop on its own thread; the destructor finishes the loop so that the
// thread can be joined.
struct loop_thread
{
ex::run_loop loop;
std::jthread thread;
loop_thread() : thread([this] { loop.run(); }) {}
~loop_thread() { loop.finish(); }
};
int main()
{
using namespace std::chrono_literals;
loop_thread worker;
ex::counting_scope scope;
// Starts now, on the worker thread.
auto answer = ex::spawn_future(
ex::schedule(worker.loop.get_scheduler())
| ex::then([]
{
std::this_thread::sleep_for(100ms);
return 42;
}),
scope.get_token());
std::println("doing other work while the computation runs");
// Collect the result when it is needed.
auto [value] = std::this_thread::sync_wait(std::move(answer)).value();
std::println("the answer is {}", value);
// The future has been consumed, so the scope can be joined.
std::this_thread::sync_wait(scope.join());
}
Output:
doing other work while the computation runs
the answer is 42
See also
(C++26) |
eagerly launches the given sender within an asynchronous scope, returning immediately without waiting for it to finish (customization point object) |
(C++26) |
tries to associate a sender with an asynchronous scope such that the scope can track the lifetime of any asynchronous operations created with the sender (customization point object) |
(C++26) |
differs from simple_counting_scope by adding support for cancellation (class) |