C++ catch块内执行Boost yield引发线程崩溃问题排查
Catch块内执行Boost Yield引发线程崩溃的排查与复现
正在排查C++环境下,因在catch块内执行Boost yield操作导致的线程崩溃场景,以下是稳定复现崩溃的核心信息:
- 必须使用
thread_group中的多线程才能触发崩溃 - 需同时运行2个协程(coroutine)
- 在catch块外执行yield时功能完全正常
- 该问题可在Mac/Win平台稳定复现(Linux未测试)
- 调试时崩溃调用栈指向catch块内的yield操作
- 曾找到提及类似问题的旧论坛讨论,但对其解释理解不清
稳定复现代码
链接Boost 1.83-1.86版本即可直接运行:
#include <boost/asio.hpp> #include <boost/asio/spawn.hpp> #include <boost/thread.hpp> #include <iostream> namespace asio = boost::asio; using namespace std::chrono_literals; void TimerCatchYield(asio::steady_timer& timer, const asio::yield_context& yield) { boost::system::error_code ec; try { throw std::runtime_error(""); } catch (const std::exception&) { // async_wait(yield) here - causes crash timer.async_wait(yield[ec]); } // async_wait(yield) here - works as expected } void coroutineA(asio::steady_timer& timer, const asio::yield_context& yield) { std::cout << "Coroutine A: Starting timer...\n"; timer.expires_after(500ms); TimerCatchYield(timer, yield); std::cout << "Coroutine A: 1\n"; timer.expires_after(500ms); TimerCatchYield(timer, yield); std::cout << "Coroutine A: 2\n"; timer.expires_after(500ms); TimerCatchYield(timer, yield); std::cout << "Coroutine A: 3\n"; std::cout << "Coroutine A: all timers expired\n"; } void coroutineB(asio::steady_timer& timer, const asio::yield_context& yield) { std::cout << "Coroutine B: Starting timer...\n"; boost::system::error_code ec; timer.expires_after(500ms); timer.async_wait(yield[ec]); std::cout << "Coroutine B: 1\n"; timer.expires_after(500ms); timer.async_wait(yield[ec]); std::cout << "Coroutine B: 2\n"; timer.expires_after(500ms); timer.async_wait(yield[ec]); std::cout << "Coroutine B: 3\n"; std::cout << "Coroutine B: all timers expired\n"; } int main() { asio::io_context io; asio::steady_timer timerA(io); asio::steady_timer timerB(io); auto strand = make_strand(io); boost::thread_group threads; spawn(strand, [&](const asio::yield_context& yield) { coroutineA(timerA, yield); }); spawn(strand, [&](const asio::yield_context& yield_b) { coroutineB(timerB, yield_b); }); for (int i = 0; i < 4; ++i) { threads.create_thread([&io]() { io.run(); }); } threads.join_all(); std::cout << "Main finished\n"; return 0; }
内容的提问来源于stack exchange,提问作者Zohar81
相关产品推荐
相关产品推荐

