[#spawn]
== cobalt/spawn.hpp

The `spawn` functions allow to run <<task, task>> on an asio `executor`/`execution_context`
and consume the result with a https://www.boost.org/doc/libs/1_83_0/doc/html/boost_asio/overview/model/completion_tokens.html[completion token].

[source,cpp]
----
auto spawn(Context & context, task<T> && t, CompletionToken&& token);
auto spawn(Executor executor, task<T> && t, CompletionToken&& token);
----

Spawn will dispatch its initiation and post the completion.
That makes it safe to use task to run the task on another executor
and consume the result on the current one with <<use_op>>.
That is, `spawn` can be used to cross threads.

=== Example

[source,cpp]
----
cobalt::task<int> work();

int main(int argc, char *argv[])
{
  asio::io_context ctx{BOOST_ASIO_CONCURRENCY_HINT_1};
  auto f = spawn(ctx, work(), asio::use_future);
  ctx.run();

  return f.get();
}
----

WARNING: The caller needs to make sure that the executor is not running on multiple threads
concurrently, e,g, by using a single-threaded `asio::io_context`.


