asio icon indicating copy to clipboard operation
asio copied to clipboard

Must call channel.close() before channel.reset(), otherwise program crashes

Open liubing opened this issue 2 years ago • 0 comments

This simple program crashes:

#ifdef _WIN32
#include <sdkddkver.h>
#endif
#include <boost/asio.hpp>
#include <boost/asio/experimental/as_tuple.hpp>
#include <boost/asio/experimental/channel.hpp>
#include <iostream>

constexpr auto use_nothrow_awaitable = boost::asio::experimental::as_tuple(boost::asio::use_awaitable);
using channel_t = boost::asio::experimental::channel<void(boost::system::error_code, int)>;

static boost::asio::awaitable<void> consume(channel_t& channel)
{
    for (;;)
    {
        auto [ec, num] = co_await channel.async_receive(use_nothrow_awaitable);
        if (!ec) std::cout << num << std::endl;
    }
}

int main()
{
    boost::asio::io_context io_context(1);
    channel_t channel(io_context, 100);
    boost::asio::co_spawn(io_context, consume(channel), boost::asio::detached);
    channel.try_send(boost::system::error_code{}, 1);
    channel.try_send(boost::system::error_code{}, 2);
    channel.reset();
    io_context.run();
    return EXIT_SUCCESS;
}

I found that calling channel.close() before channel.reset() fixed the problem, is it supposed to be normal?

liubing avatar Mar 16 '22 02:03 liubing