strand::running_in_this_thread()误报问题及调度影响咨询
关于Asio Strand的running_in_this_thread()行为疑问
这是一段使用Asio协程的代码示例(假设已包含Asio头文件并添加必要的using指令):
io_context _io_ctx; auto _strand1 = make_strand(_io_ctx); auto _strand2 = make_strand(_io_ctx); asio::awaitable<void> g() { auto ex = co_await asio::this_coro::executor; assert(_strand1.running_in_this_thread()); // *** 该断言本应失败,但实际未失败 assert(_strand2.running_in_this_thread()); // 以下行可替换为`sleep(1)`,效果相同 co_await steady_timer{ex, std::chrono::milliseconds{10}}.async_wait(use_awaitable); assert(!_strand1.running_in_this_thread()); // 此处行为符合预期 assert(_strand2.running_in_this_thread()); co_return; } asio::awaitable<void> f() { auto ex = co_await asio::this_coro::executor; for (;;) { assert(_strand1.running_in_this_thread()); assert(!_strand2.running_in_this_thread()); co_await steady_timer{ex, std::chrono::milliseconds{5}}.async_wait(use_awaitable); assert(_strand1.running_in_this_thread()); assert(!_strand2.running_in_this_thread()); co_spawn(_strand2, g, detached); } } int main() { co_spawn(_strand1, f, detached); _io_ctx.run(); }
该程序运行在单线程环境下(虽然这里使用strand没有实际并发保护的意义,但strand本身仍应遵循其行为规范)。核心疑问是:为什么在协程g()中,两个strand的running_in_this_thread()都返回true?这种行为会对strand的函数调度产生什么影响?
我猜测strand不会主动修改内部状态来报告“未处于运行中”,从而导致了这个误报。
编辑补充
在多线程运行io_context的场景下,协程g()中首次调用_strand1.running_in_this_thread()的结果是不可预测的。我推测这取决于g()是否在调用co_spawn的同一线程上紧随f()运行。
内容的提问来源于stack exchange,提问作者DeltA
相关产品推荐
相关产品推荐

