A task is a lazy coroutine that can co_await
and co_return
values. That is, it cannot use co_yield
.
cobalt::task<void> delay(std::chrono::milliseconds ms)
{
asio::steady_timer tim{co_await cobalt::this_coro::executor, ms};
co_await tim.async_wait(cobalt::use_op);
}
cobalt::main co_main(int argc, char *argv[])
{
co_await delay(std::chrono::milliseconds(50));
co_return 0;
}
Unlike a promise, a task can be awaited or spawned on another executor than it was created on.
Since a task
it lazy, it does not need to have an executor on construction.
It rather attempts to take it from the caller or awaiter if present.
Otherwise, it’ll default to the thread_local executor.
The memory resource is NOT taken from the thread_local
get_default_resource function,
but pmr::get_default_resource(),
unless a `std::allocator_arg
is used in any position followed by a polymorphic_allocator
argument.
cobalt::task<int> my_gen(std::allocator_arg_t, pmr::polymorphic_allocator<void> alloc);
link:../../include/boost/cobalt/task.hpp[role=include]
Note
|
Tasks can be used synchronously from a sync function by calling run(my_task()) .
|
The task promise has the following properties.
The use_task
completion token can be used to create a task from an cobalt_
function.
This is less efficient than use_op as it needs to allocate a coroutine frame,
but has a simpler return type and supports [interrupt_await].