Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

co_spawn (1 of 6 overloads)

Spawn a new coroutined-based thread of execution.

template<
    typename Executor,
    typename T,
    typename AwaitableExecutor,
    typename CompletionToken = DEFAULT>
DEDUCED co_spawn(
    const Executor & ex,
    awaitable< T, AwaitableExecutor > a,
    CompletionToken && token = DEFAULT,
    typename constraint< (is_executor< Executor >::value||execution::is_executor< Executor >::value)&&is_convertible< Executor, AwaitableExecutor >::value >::type  = 0);
Parameters

ex

The executor that will be used to schedule the new thread of execution.

a

The awaitable object that is the result of calling the coroutine's entry point function.

token

The completion token that will handle the notification that the thread of execution has completed. The function signature of the completion handler must be:

void handler(std::exception_ptr, T);

Example
boost::asio::awaitable<std::size_t> echo(tcp::socket socket)
{
  std::size_t bytes_transferred = 0;

  try
  {
    char data[1024];
    for (;;)
    {
      std::size_t n = co_await socket.async_read_some(
          boost::asio::buffer(data), boost::asio::use_awaitable);

      co_await boost::asio::async_write(socket,
          boost::asio::buffer(data, n), boost::asio::use_awaitable);

      bytes_transferred += n;
    }
  }
  catch (const std::exception&)
  {
  }

  co_return bytes_transferred;
}

// ...

boost::asio::co_spawn(my_executor,
  echo(std::move(my_tcp_socket)),
  [](std::exception_ptr e, std::size_t n)
  {
    std::cout << "transferred " << n << "\n";
  });

PrevUpHomeNext