[asio-users] Does co_spawn start a coroutine lazily ?
Brought to you by:
chris_kohlhoff
From: Eduardo P. <edu...@gm...> - 2023-07-05 00:05:34
|
I am using asio and C++20 coroutines to wait for a socket to become ready for read or write. Please, see example below: asio::awaitable<void> waitForIO(asio::ip::tcp::socket& socket, asio::socket_base::wait_type waitType) { std::cout << "start waiting for " << (waitType ==asio::socket_base::wait_type::wait_write ? "write" : "read") << std::endl; // line 1 co_await socket.async_wait(waitType, use_awaitable); // line 2 std::cout << "socket became ready to " << (waitType ==asio::socket_base::wait_type::wait_write ? "write" : "read") << std::endl; // line 3 } void startIO() { std::cout << "spawning write coroutine" << std::endl; // line 4 asio::co_spawn(socket->get_executor(), waitForIO(socket, socket, asio::socket_base::wait_type::wait_write), asio::detached); // line 5 std::cout << "spawning read coroutine" << std::endl; // line 6 asio::co_spawn(socket->get_executor(), waitForIO(socket, asio::socket_base::wait_type::wait_read), asio::detached); // line 7 } Note: At the point where I am spawning the coroutines the respective io executor is already running. I assume I will always get the sequence (co_spawn immediately makes coroutine to execute line 2 - wait for read/write): 1. spawning write coroutine 2. start waiting for write 3. spawning read coroutine 4. start waiting for read I am wondering whether co_spawn can instead produce sequences like below: A - does not immediately start to wait for read or write: 1. spawning write coroutine 2. spawning read coroutine 3. start waiting for write 4. start waiting for read B - Becomes ready to write (or socket is cancelled) before waiting for read: 1. spawning write coroutine 2. spawning read coroutine 3. start waiting for write 4. socket became ready to write 5. start waiting for read Thanks, Eduardo Panisset. |