[关闭]
@john-lee 2021-01-03T03:58:20.000000Z 字数 891 阅读 873

无栈协程(Stackless Coroutines)

Boost.Asio


coroutine类提供对无栈协程的支持。无栈协程使程序能够用最小的开销以同步方式实现异步逻辑,如下例所示:

  1. struct session : boost::asio::coroutine
  2. {
  3. boost::shared_ptr<tcp::socket> socket_;
  4. boost::shared_ptr<std::vector<char> > buffer_;
  5. session(boost::shared_ptr<tcp::socket> socket)
  6. : socket_(socket),
  7. buffer_(new std::vector<char>(1024))
  8. {
  9. }
  10. void operator()(boost::system::error_code ec = boost::system::error_code(), std::size_t n = 0)
  11. {
  12. if (!ec) reenter (this)
  13. {
  14. for (;;)
  15. {
  16. yield socket_->async_read_some(boost::asio::buffer(*buffer_), *this);
  17. yield boost::asio::async_write(*socket_, boost::asio::buffer(*buffer_, n), *this);
  18. }
  19. }
  20. }
  21. };

coroutine类与伪关键字reenteryieldfork一起使用。这些都是预处理器宏,使用类似于达夫装置(Duff's Device)的技术,通过switch语句实现。coroutine类的文档提供了这些伪关键字的完整描述。

另请参阅

coroutine,HTTP 服务器 4 的例子,有栈协程。


Copyright © 2003-2020 Christopher M. Kohlhoff

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注