chriskohlhoff / asio

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

why i don't see that handler cancellation signal is invoked here? #1549

Open linoxoidunix opened 3 weeks ago

linoxoidunix commented 3 weeks ago

include <boost/asio.hpp>

include

include

include // for std::reference_wrapper

namespace net = boost::asio;

net::cancellation_slot unify_cancellation_signals(net::cancellation_signal& unified_signal, std::vector<std::reference_wrapper>& signals) {

for (auto& signal : signals) {
    signal.get().slot().assign([&](net::cancellation_type type) {
        unified_signal.emit(type);
    });
}

return unified_signal.slot();

}

net::awaitable cancellable_operation(net::cancellation_slot& slot) { auto executor = co_await net::this_coro::executor;

net::steady_timer timer(executor, std::chrono::seconds(10));

try {
    co_await timer.async_wait(net::bind_cancellation_slot(slot, net::use_awaitable));
    std::cout << "Operation completed.\n";
} catch (const boost::system::system_error& e) {
    if (e.code() == net::error::operation_aborted) {
        std::cout << "Operation cancelled.\n";
    } else {
        throw;
    }
}

}

int main() { boost::asio::thread_pool io; //net::io_context io;

net::cancellation_signal signal1, signal2;
net::cancellation_signal unified_signal;

std::vector<std::reference_wrapper<net::cancellation_signal>> signals = {signal1, signal2};

net::cancellation_slot unified_slot = unify_cancellation_signals(unified_signal, signals);

unified_slot.assign([](boost::asio::cancellation_type_t&) {
     std::cout << "Cancellation requested!" << std::endl;
 });

net::co_spawn(io, cancellable_operation(unified_slot), net::detached);
//std::this_thread::sleep_for(std::chrono::seconds(3));

net::steady_timer delay_timer(io, std::chrono::nanoseconds(1));
delay_timer.async_wait([&](const boost::system::error_code&) {
    std::cout << "Emitting cancellation signal...\n";
    signal2.emit(net::cancellation_type::all);
});

//signal1.emit(net::cancellation_type::all);

//io.run();
io.join();

}