Boost Asio中co_spawn与spawn作为异步发起函数引发段错误
Boost Asio中栈式协程嵌套spawn/co_spawn触发段错误的问题
在项目中同时使用Boost Asio的栈式协程和C++20协程时,发现特定调用顺序下会触发段错误,以下是具体场景:
正常运行的示例
以下代码可无错误运行,spawn可作为普通异步操作被co_await:
#include <boost/asio.hpp> #include <boost/asio/awaitable.hpp> #include <boost/asio/spawn.hpp> #include <iostream> using namespace boost::asio; io_context ioctx; void stackful_coroutine(yield_context yield); awaitable<void> cxx_coroutine() { std::cout << "In cxx_coroutine" << std::endl; co_await spawn(ioctx, stackful_coroutine, use_awaitable); co_return; } void stackful_coroutine(yield_context yield) { std::cout << "In stackful_coroutine" << std::endl; } int main() { co_spawn(ioctx, cxx_coroutine(), detached); ioctx.run(); }
调换调用顺序后触发段错误
将调用顺序调换,在栈式协程内部调用co_spawn并传入yield_context作为完成令牌时,程序出现段错误:
#include <boost/asio.hpp> #include <boost/asio/awaitable.hpp> #include <boost/asio/spawn.hpp> #include <iostream> using namespace boost::asio; io_context ioctx; void stackful_coroutine(yield_context yield); awaitable<void> cxx_coroutine() { std::cout << "In cxx_coroutine" << std::endl; co_return; } void stackful_coroutine(yield_context yield) { std::cout << "In stackful_coroutine" << std::endl; co_spawn(ioctx, cxx_coroutine(), yield); } int main() { spawn(ioctx, stackful_coroutine, detached); ioctx.run(); }
纯栈式协程嵌套spawn也触发段错误
即使不涉及C++20协程,仅在栈式协程内部嵌套调用spawn并传入yield_context,同样会出现段错误:
#include <boost/asio.hpp> #include <boost/asio/awaitable.hpp> #include <boost/asio/spawn.hpp> #include <iostream> using namespace boost::asio; io_context ioctx; void stackful_coroutine(yield_context yield) { std::cout << "In stackful_coroutine" << std::endl; spawn( ioctx, [](auto yc) { std::cout << "Spawn inside spawn" << std::endl; }, yield); } int main() { spawn(ioctx.get_executor(), stackful_coroutine, detached); ioctx.run(); }
当前使用环境:gcc (Debian 12.2.0-14) 12.2.0,Boost 1.83.0。不确定这是Boost Asio的bug,还是用法上存在疏漏,寻求解答。
内容的提问来源于stack exchange,提问作者Suraaj K S
相关产品推荐
相关产品推荐

