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

spawn

Start a new stackful coroutine.

template<
    typename Function>
void spawn(
    Function && function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());
  » more...

template<
    typename Handler,
    typename Function>
void spawn(
    Handler && handler,
    Function && function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes(),
    typename enable_if<!is_executor< typename decay< Handler >::type >::value &&!is_convertible< Handler &, execution_context & >::value >::type *  = 0);
  » more...

template<
    typename Handler,
    typename Function>
void spawn(
    basic_yield_context< Handler > ctx,
    Function && function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());
  » more...

template<
    typename Function,
    typename Executor>
void spawn(
    const Executor & ex,
    Function && function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes(),
    typename enable_if< is_executor< Executor >::value >::type *  = 0);
  » more...

template<
    typename Function,
    typename Executor>
void spawn(
    const strand< Executor > & ex,
    Function && function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());
  » more...

template<
    typename Function>
void spawn(
    const boost::asio::io_context::strand & s,
    Function && function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes());
  » more...

template<
    typename Function,
    typename ExecutionContext>
void spawn(
    ExecutionContext & ctx,
    Function && function,
    const boost::coroutines::attributes & attributes = boost::coroutines::attributes(),
    typename enable_if< is_convertible< ExecutionContext &, execution_context & >::value >::type *  = 0);
  » more...

The spawn() function is a high-level wrapper over the Boost.Coroutine library. This function enables programs to implement asynchronous logic in a synchronous manner, as illustrated by the following example:

boost::asio::spawn(my_strand, do_echo);

// ...

void do_echo(boost::asio::yield_context yield)
{
  try
  {
    char data[128];
    for (;;)
    {
      std::size_t length =
        my_socket.async_read_some(
          boost::asio::buffer(data), yield);

      boost::asio::async_write(my_socket,
          boost::asio::buffer(data, length), yield);
    }
  }
  catch (std::exception& e)
  {
    // ...
  }
}
Requirements

Header: boost/asio/spawn.hpp

Convenience header: None


PrevUpHomeNext