How to cancel a coroutine created by boost::asio::spawn

Viewed 398

I use boost::asio::spawn to start a coroutine

boost::asio::io_context ioc;
boost::asio::steady_timer timer(ioc);
boost::asio::ip::tcp::socket socket(ioc);
boost::asio::io_context::strand strand(ioc);
......
boost::asio::spawn(strand, [&](boost::asio::yield_context yield)
{
    while(true){
        http::async_write(socket, req_indicators, yield);
        http::async_read(socket, buffer, res, yield);
        // do something with res
        timer.expires_after(interval);
        timer.async_wait(yield);
    }
}
......

Now I want to cancel this coroutine immediately (no waiting for timer to expire and check a flag) without stopping the entire ioc, because there are other coroutines running in the same strand.

I can call timer.cancel() and socket.close() together, but as the coroutine gets complicated, I have to keep track of everything that can cause a yield in the coroutine, which is tiresome and error prone. Is there a method to unconditionally stop a coroutine created by boost::asio::spawn, like python's asyncio.task.cancel()?

0 Answers
Related