std::execution::task
| Defined in header <execution>
|
||
template< class T = void, class Environment = env<> >
class task;
|
(since C++26) | |
task is the return type of coroutines that run as asynchronous operations of std::execution. A task is a sender: calling a coroutine that returns task<T> creates the coroutine and returns the task without running any of the coroutine body. The body starts running when the task is connected to a receiver and started, for example by std::this_thread::sync_wait, or by co_await in another coroutine that returns a task.
Inside the coroutine:
co_returnvalue;completes the task withset_value(value), converted toT; ifTisvoid,co_return;or the end of the body completes it withset_value().- An exception that leaves the body completes the task with
set_error(std::exception_ptr). Ifset_error_t(std::exception_ptr)is not one of the error completions of the task, std::terminate is called instead. co_yield execution::with_error(err);completes the task with an error without throwing an exception: withset_error(err), converted to the one error type of the task that it converts to. The coroutine does not resume.co_await sndrstarts the sendersndr, which can be another task, and suspends the coroutine until the sender completes. The sender must have at most one kind of value completion. If it completes with a value, theco_awaitexpression evaluates to it: tovoidif there is no value, to the value if there is one, and to a std::tuple of the values if there are several. If it completes with an error, the error is thrown as an exception: a std::exception_ptr is rethrown, a std::error_code is thrown as std::system_error, and any other error is thrown as it is. If it completes with set_stopped, the coroutine is not resumed: it is destroyed, and the task completes withset_stopped.
The coroutine state, with the local variables of the coroutine, is destroyed before the task calls the completion function on its receiver.
Scheduler affinity
After co_await, the coroutine resumes on the scheduler on which the task was started, even if the awaited sender completed on another one. A task is started by a receiver whose environment provides that scheduler through get_start_scheduler, and the task keeps it as a start_scheduler_type, by default task_scheduler. Awaited senders are passed through affine, which schedules the rest of the coroutine back on that scheduler; for senders that are known to complete where they were started, such as just, the implementation can skip the rescheduling.
To run some work elsewhere, await it with an algorithm that starts it on another scheduler, such as co_await execution::starts_on(sch, work): the work runs on sch, and the coroutine continues on its own scheduler afterwards. If start_scheduler_type is inline_scheduler, the task has no affinity: the coroutine resumes wherever the awaited sender completes.
Template parameters
| T | - | the type of the value that the task completes with: void for no value, a reference type, or a non-array object type that is not cv-qualified
|
| Environment | - | a class type that customizes the task; see below |
The following members of Environment are used if they exist:
| Member | Meaning |
allocator_type
|
the allocator type used for the coroutine state and for the environment of awaited senders |
start_scheduler_type
|
the type that stores the scheduler the task was started on |
stop_source_type
|
the type of the stop source the task creates if the stop token of its receiver has a different type |
error_types
|
a specialization of completion_signatures that lists the error completions of the task, each of the form set_error_t(E)
|
env_type<RcvrEnv>
|
a template, specialized for the type of the environment of the receiver, whose object is constructed from that environment when the task is connected; the Environment object is then constructed from it if possible, otherwise from the environment of the receiver, otherwise by default
|
Queries of the environment of awaited senders that are not answered by the task, and that are forwarding queries, are answered by the Environment object.
Member types
| Member type | Definition |
sender_concept
|
sender_tag |
allocator_type
|
Environment::allocator_type if present, otherwise std::allocator<std::byte>
|
start_scheduler_type
|
Environment::start_scheduler_type if present, otherwise task_scheduler
|
stop_source_type
|
Environment::stop_source_type if present, otherwise std::inplace_stop_source
|
stop_token_type
|
the type of the token returned by stop_source_type::get_token()
|
error_types
|
Environment::error_types if present, otherwise completion_signatures<set_error_t(std::exception_ptr)>
|
promise_type
|
the promise type of the coroutine |
Member functions
(constructor) |
move constructor; the moved-from task is empty. A task is not copyable (function) |
(destructor) |
destroys the coroutine, if the task holds one that has not been connected (function) |
get_completion_signatures |
returns a completion_signatures object whose type lists, in unspecified order, the value completion signature (set_value_t() if T is void, or set_value_t(T) otherwise), the error completion signatures in error_types, and the stopped completion signature set_stopped_t()(static consteval) (function template) |
connect |
connects the task to a receiver; the task must be an rvalue, and the coroutine is moved into the operation state (function) |
Environment of awaited senders
A sender awaited in the coroutine is connected to a receiver whose environment answers:
- get_start_scheduler with the scheduler the task was started on;
- get_allocator with the allocator of the environment of the task's receiver, converted to
allocator_type, or withallocator_type()if that environment has none; - get_stop_token with the stop token of the task's receiver. If its type is not
stop_token_type, the task creates astop_source_typethat is stopped when that token is, and answers with a token of that source; - forwarding queries answered by the
Environmentobject.
co_await execution::read_env(q) returns the result of a query q, for example the stop token of the task with co_await execution::read_env(std::get_stop_token).
Allocation
The coroutine state is allocated with allocator_type(). A coroutine can be given another allocator by declaring std::allocator_arg_t and an allocator as its first parameters, or as its first parameters after the object parameter of a member function, and the caller passes std::allocator_arg and the allocator. The allocator can be of any type, not only allocator_type.
Notes
- A task can be started only by a receiver whose environment provides a scheduler through get_start_scheduler, unless
start_scheduler_typeis default constructible, as inline_scheduler is. std::this_thread::sync_wait andco_awaitin a task provide one, and so does starts_on, but spawn does not by itself:spawn(starts_on(sch, t), token)provides one. Sincespawnalso requires a sender that cannot complete with an error, a task that it starts usually also needs upon_error, orerror_typeswithout error completions. - The scheduler that a task is started on must be able to resume the coroutine without failing: its
schedulesender can only complete withset_value, or also withset_stoppedif stop can be requested. Otherwise, the program is ill-formed. - The coroutine body runs only when the task is started, which can be long after the coroutine was called. A parameter that is a reference must still refer to a valid object at that time; parameters passed by value are copied into the coroutine state and are safe.
- A task holds its coroutine until it is connected, and can be connected only once.
- A task can be awaited in a coroutine that returns a
task, but not directly in coroutines of other types: it has nooperator co_await, and as a sender it needs a receiver that provides a start scheduler and can accept a stopped completion (LWG issue 4338). - Earlier drafts had
co_await change_coroutine_scheduler(sch)to switch the scheduler of the running coroutine. It was removed before C++26 was published;co_await execution::starts_on(sch, work)runs work on another scheduler. - In typical implementations (stdexec, beman.execution), the only data member of a
taskis the handle of its coroutine.connectmoves the handle into the operation state, which also holds the receiver, the start scheduler, and the environment object. The result and the stop source are kept either in the operation state or in the coroutine state.startresumes the coroutine. Calling a coroutine that returns ataskallocates the coroutine state and nothing else. Awaiting that task in another task does not allocate any more memory.
Example
total awaits other tasks, catches the exception that one of them throws, and awaits work that runs on another thread. The coroutine resumes on the thread where it was started, which is the main thread, the one sync_wait runs on.
The execution control library components may not be available in the online compilers yet, so this link runs the example on Compiler Explorer with stdexec (one of the reference implementations).
#include <execution>
#include <print>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
namespace ex = std::execution;
// The body does not run until the task is started, here by co_await
ex::task<int> parse(std::string text)
{
if (text.empty())
throw std::invalid_argument("empty input");
co_return std::stoi(text);
}
ex::task<int> total(std::vector<std::string> items, ex::scheduler auto worker)
{
int sum = 0;
for (const auto& item : items)
{
try
{
sum += co_await parse(item);
}
catch (const std::invalid_argument& e)
{
std::println("Skipped: {}", e.what());
}
}
// Some work on another thread: after it, the coroutine resumes on the
// thread where the task was started
auto started_on = std::this_thread::get_id();
auto ran_on = co_await ex::starts_on(worker, ex::just() | ex::then([]
{
return std::this_thread::get_id();
}));
std::println("The work ran on another thread: {}", ran_on != started_on);
std::println("Resumed on the starting thread: {}",
std::this_thread::get_id() == started_on);
co_return sum;
}
int main()
{
ex::run_loop loop;
std::jthread worker_thread([&loop] { loop.run(); });
auto work = total({"1", "2", "", "39"}, loop.get_scheduler());
auto [sum] = std::this_thread::sync_wait(std::move(work)).value();
std::println("Total: {}", sum);
loop.finish();
}
Output:
Skipped: empty input
The work ran on another thread: true
Resumed on the starting thread: true
Total: 42
See also
(C++26) |
holds an error that a task coroutine passes to co_yield to complete with that error (class template) |
(C++26) |
provides a uniform, type-erased interface, which allows to store, pass around, and invoke scheduling operations on arbitrary infallible schedulers (class) |
(C++26) |
a trivial scheduler that completes immediately and synchronously on the thread that calls std::execution::start on the operation state produced by its sender (class) |
(C++26) |
adapts a sender into one that completes on the scheduler the operation was started on (customization point object) |
(C++26) |
transforms an expression into awaitable object within a particular coroutine (customization point object) |
| when used as the base class of a coroutine promise type, enables senders to be awaitable within that coroutine type (class template) | |
| asks a queryable object for the scheduler an operation will be or was started on (customization point object) |