asio C++ library

PrevUpHomeNext

co_spawn (2 of 6 overloads)

Spawn a new coroutined-based thread of execution.

template<
    typename Executor,
    typename AwaitableExecutor,
    typename CompletionToken = DEFAULT>
DEDUCED co_spawn(
    const Executor & ex,
    awaitable< void, AwaitableExecutor > a,
    CompletionToken && token = DEFAULT,
    constraint_t<(is_executor< Executor >::value||execution::is_executor< Executor >::value) &&is_convertible< Executor, AwaitableExecutor >::value >  = 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);
Completion Signature
void(std::exception_ptr)
Example
asio::awaitable<void> echo(tcp::socket socket)
{
  try
  {
    char data[1024];
    for (;;)
    {
      std::size_t n = co_await socket.async_read_some(
          asio::buffer(data), asio::use_awaitable);

      co_await asio::async_write(socket,
          asio::buffer(data, n), asio::use_awaitable);
    }
  }
  catch (const std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }
}

// ...

asio::co_spawn(my_executor,
  echo(std::move(my_tcp_socket)),
  asio::detached);
Per-Operation Cancellation

The new thread of execution is created with a cancellation state that supports cancellation_type::terminal values only. To change the cancellation state, call this_coro::reset_cancellation_state.


PrevUpHomeNext