coroutine.qbk 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. [/
  2. / Copyright (c) 2003-2019 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. [section:coroutine Stackless Coroutines]
  8. The [link boost_asio.reference.coroutine `coroutine`] class provides support for
  9. stackless coroutines. Stackless coroutines enable programs to implement
  10. asynchronous logic in a synchronous manner, with minimal overhead, as shown in
  11. the following example:
  12. struct session : boost::asio::coroutine
  13. {
  14. boost::shared_ptr<tcp::socket> socket_;
  15. boost::shared_ptr<std::vector<char> > buffer_;
  16. session(boost::shared_ptr<tcp::socket> socket)
  17. : socket_(socket),
  18. buffer_(new std::vector<char>(1024))
  19. {
  20. }
  21. void operator()(boost::system::error_code ec = boost::system::error_code(), std::size_t n = 0)
  22. {
  23. if (!ec) reenter (this)
  24. {
  25. for (;;)
  26. {
  27. yield socket_->async_read_some(boost::asio::buffer(*buffer_), *this);
  28. yield boost::asio::async_write(*socket_, boost::asio::buffer(*buffer_, n), *this);
  29. }
  30. }
  31. }
  32. };
  33. The `coroutine` class is used in conjunction with the pseudo-keywords
  34. `reenter`, `yield` and `fork`. These are preprocessor macros, and are
  35. implemented in terms of a `switch` statement using a technique similar to
  36. Duff's Device. The [link boost_asio.reference.coroutine `coroutine`] class's
  37. documentation provides a complete description of these pseudo-keywords.
  38. [heading See Also]
  39. [link boost_asio.reference.coroutine coroutine],
  40. [link boost_asio.examples.cpp03_examples.http_server_4 HTTP Server 4 example],
  41. [link boost_asio.overview.core.spawn Stackful Coroutines].
  42. [endsect]