• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1[/
2 / Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com)
3 /
4 / Distributed under the Boost Software License, Version 1.0. (See accompanying
5 / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 /]
7
8[section:coroutine Stackless Coroutines]
9
10The [link boost_asio.reference.coroutine `coroutine`] class provides support for
11stackless coroutines. Stackless coroutines enable programs to implement
12asynchronous logic in a synchronous manner, with minimal overhead, as shown in
13the following example:
14
15  struct session : boost::asio::coroutine
16  {
17    boost::shared_ptr<tcp::socket> socket_;
18    boost::shared_ptr<std::vector<char> > buffer_;
19
20    session(boost::shared_ptr<tcp::socket> socket)
21      : socket_(socket),
22        buffer_(new std::vector<char>(1024))
23    {
24    }
25
26    void operator()(boost::system::error_code ec = boost::system::error_code(), std::size_t n = 0)
27    {
28      if (!ec) reenter (this)
29      {
30        for (;;)
31        {
32          yield socket_->async_read_some(boost::asio::buffer(*buffer_), *this);
33          yield boost::asio::async_write(*socket_, boost::asio::buffer(*buffer_, n), *this);
34        }
35      }
36    }
37  };
38
39The `coroutine` class is used in conjunction with the pseudo-keywords
40`reenter`, `yield` and `fork`. These are preprocessor macros, and are
41implemented in terms of a `switch` statement using a technique similar to
42Duff's Device. The [link boost_asio.reference.coroutine `coroutine`] class's
43documentation provides a complete description of these pseudo-keywords.
44
45[heading See Also]
46
47[link boost_asio.reference.coroutine coroutine],
48[link boost_asio.examples.cpp03_examples.http_server_4 HTTP Server 4 example],
49[link boost_asio.overview.core.spawn Stackful Coroutines].
50
51[endsect]
52