chriskohlhoff / asio

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

Can I use coroutines and thread pools this way? or how do I use them when I want to take full advantage of multiple CPU cores? #1508

Open kumoki opened 4 months ago

kumoki commented 4 months ago
awaitable<void> listener()
{
    auto executor = co_await this_coro::executor;
    tcp::acceptor acceptor(executor, {tcp::v4(), 55555});
    asio::thread_pool pool(4);
    for (;;)
    {
        tcp::socket socket = co_await acceptor.async_accept(use_awaitable);
        co_spawn(pool, func(std::move(socket)), detached);
    }
}

int main()
{
    asio::io_context io_context(1);

    asio::signal_set signals(io_context, SIGINT, SIGTERM);
    signals.async_wait([&](auto, auto){ io_context.stop(); });

    co_spawn(io_context, listener(), detached);

    io_context.run();
}