Is it safe to use spawn directly in an asio stackful coroutine?

大城市里の小女人 提交于 2019-12-03 18:00:38
Tanner Sansbury

It is safe.

Boost.Asio's first-class support for Boost.Coroutine is a thin facade with two notable behaviors:

  • A coroutine and handlers which resume it use a strand for their execution context. This guarantees the coroutine will not be resumed before it has yielded.
  • Boost.Asio prevents a coroutine from staying indefinitely suspended if it detects that there are no handlers available to resume it. When this occurs, Boost.Asio will destroy the coroutine, causing the suspended stack to unwind. See this answer for more details.

In the example code above, the spawn(io_service&) overload causes the resulting coroutine to have its own strand. As a result, if multiple threads are running the io_service, each of the coroutines may run in parallel, but are not guaranteed to do so. On the other hand, if one uses the spawn(yield_context) overload, the new coroutine will have the same execution context (i.e strand) as the calling coroutine, preventing parallel execution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!