[#task]
== cobalt/task.hpp

A task is a lazy coroutine that can `co_await` and `co_return` values. That is, it cannot use `co_yield`.

[source,cpp]
----
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, promise>>, a task can be awaited or spawned on another executor than it was created on.

=== Executor
[#task-executor]

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.

=== Memory Resource
[#task-allocator]

The memory resource is *NOT* taken from the `thread_local` <<this_thread, 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.

[source, cpp]
----
cobalt::task<int> my_gen(std::allocator_arg_t, pmr::polymorphic_allocator<void> alloc);
----

[#task-outline]
=== Outline


[source,cpp]
----
include::../../include/boost/cobalt/task.hpp[tag=outline]
----

NOTE: Tasks can be used synchronously from a sync function by calling `run(my_task())`.


[#task-task]
=== Promise

The task promise has the following properties.

- <<promise_memory_resource_base>>
- <<promise_cancellation_base>>
- <<promise_throw_if_cancelled_base>>
- <<enable_awaitables>>
- <<enable_await_allocator>>
- <<enable_await_executor>>
- <<enable_await_deferred>>

[#use_task]
=== use_task

The `use_task` completion token can be used to create a task from an `cobalt_` function.
This is less efficient than <<use_op, use_op>> as it needs to allocate a coroutine frame,
but has a simpler return type and supports <<interrupt_await>>.

