chriskohlhoff / asio

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

Why channel::close() doesn't cancel async_send()? #1318

Open zagrichanskiy opened 1 year ago

zagrichanskiy commented 1 year ago

Hey guys,

Maybe someone can explain the rationale behind why when we close the channel only async_receive() is cancelled?

The following snippet hangs:

#include <iostream>

#include <asio.hpp>
#include <asio/experimental/channel.hpp>

using namespace asio;
using namespace asio::experimental;
using namespace std::chrono_literals;

int main()
{
    asio::io_context ctx;
    asio::experimental::channel<void(std::error_code, int)> ch(ctx.get_executor());

    ch.async_send({}, 1, [] (std::error_code ec)
    {
        std::cout << "send ec: " << ec.message() << std::endl;
    });

    steady_timer timer(ctx, 1s);
    timer.async_wait([&] (auto)
    {
        ch.close();
    });

    ctx.run();

    return 0;
}

Any way to make this no hang? thanks