Cancellable timers: sorted_list::remove, timer cancel, replace done flag with timer cancellation

This commit is contained in:
Ian Gulliver
2026-04-11 08:28:32 +09:00
parent 3a3c5873c3
commit e486f6501a
5 changed files with 48 additions and 18 deletions

View File

@@ -17,8 +17,12 @@ void dispatch_init() {
dlog("dispatch_init complete");
}
void dispatch_schedule_ms(uint32_t ms, std::function<void()> fn) {
timers.schedule_ms(ms, std::move(fn));
timer_handle dispatch_schedule_ms(uint32_t ms, std::function<void()> fn) {
return timers.schedule_ms(ms, std::move(fn));
}
bool dispatch_cancel_timer(timer_handle h) {
return timers.cancel(h);
}
[[noreturn]] void dispatch_run(std::span<const handler_entry> handlers) {

View File

@@ -30,27 +30,24 @@ static void test_ping(const responder& resp, ipv4::ip4_addr dst_ip) {
ipv4::ip4_addr our_ip = ns.ip;
auto done = std::make_shared<bool>(false);
auto timer = std::make_shared<timer_handle>(nullptr);
auto cb = std::make_shared<std::function<void(std::span<const uint8_t>)>>();
*cb = [resp, ping_id, our_ip, done, cb](std::span<const uint8_t> frame) {
if (*done) return;
*cb = [resp, ping_id, our_ip, timer, cb](std::span<const uint8_t> frame) {
ipv4::ip4_addr src_ip;
if (!icmp::parse_echo_reply(frame, src_ip, ping_id)) {
net_add_frame_callback(*cb);
return;
}
dispatch_cancel_timer(*timer);
if (src_ip == our_ip) {
net_add_frame_callback(*cb);
resp.respond(ResponseTest{false, {"got reply from self: " + ipv4::to_string(src_ip)}});
return;
}
*done = true;
resp.respond(ResponseTest{true, {"reply from " + ipv4::to_string(src_ip)}});
};
net_add_frame_callback(*cb);
dispatch_schedule_ms(5000, [resp, done]() {
if (*done) return;
*done = true;
*timer = dispatch_schedule_ms(5000, [resp]() {
resp.respond(ResponseTest{false, {"no reply from non-self host within 5s"}});
});
}