2
0
mirror of https://github.com/boostorg/cobalt.git synced 2026-01-19 04:02:16 +00:00
Files
cobalt/doc/reference/spawn.adoc
Klemens Morgenstern 45901641ac renamed to cobalt.
2023-10-16 21:42:07 +08:00

38 lines
1.1 KiB
Plaintext

[#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` or a `strand`.