You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 01:40:24