chriskohlhoff / asio

Asio C++ Library
http://think-async.com/Asio
4.97k stars 1.22k forks source link

Failed to switch thread to specified executor thread using dispatch in coroutine #1516

Closed zhllxt closed 3 months ago

zhllxt commented 3 months ago
asio::awaitable<void> test(asio::io_context& ctx2)
{
    fmt::print("coro thread: {}\n", std::this_thread::get_id());
    // output: 18472 == thread1

    co_await asio::dispatch(ctx2.get_executor(), asio::use_awaitable);

    fmt::print("thread after coro switch: {}\n", std::this_thread::get_id());
    // output: 18472 == thread1, switch failed

    asio::dispatch(ctx2.get_executor(), [&]() mutable
    {
        fmt::print("thread after async switch: {}\n", std::this_thread::get_id());
        // output: 7652 == thread2, switch successed
    });
}

int main()
{
    asio::io_context ctx1, ctx2;

    asio::co_spawn(ctx1.get_executor(), test(ctx2), asio::detached);

    std::thread([&]() mutable
    {
        fmt::print("thread1: {}\n", std::this_thread::get_id()); // output: 18472
        while (true)
            ctx1.run();
    }).detach();

    std::thread([&]() mutable
    {
        fmt::print("thread2: {}\n", std::this_thread::get_id()); // output: 7652
        while (true)
            ctx2.run();
    }).detach();

    while (std::getchar() != '\n');
}
zhllxt commented 3 months ago

ok, i know.

co_await asio::dispatch(asio::bind_executor(ctx2.get_executor(), asio::use_awaitable));