asio using both coroutine and thread_pool issue

28 views Asked by At

I'm writing a tcp server using both asio::thread_pool and coroutine, but I'm not sure if the below code is correct, I want each message handle function scheduled like task in goroutine, so should I call co_spawn or just co_await handler(message) in the lamda function?

by the way, what did co_spawn actually do? when should I use it?

awaitable<void> TcpServer::Serve(tcp::socket socket)
{
    try
    {
        for (;;)
        {
            // read message and error handle

            auto executor = co_await this_coro::executor;
            asio::post(thread_pool_, 
                [&, this]() -> asio::awaitable<void>{
                    co_spawn(executor, handler(message), detached);
            });
        }
    }
    catch (std::exception &e)
    {
        // ....
    }
}
0

There are 0 answers