//! A one-shot cancel signal that every waiter can block on. const std = @import("std"); /// Set by whoever wants the work to stop; every waiter wakes at once. pub const Abort = struct { event: std.Io.Event = .unset, pub fn set(self: *Abort, io: std.Io) void { self.event.set(io); } pub fn isSet(self: *const Abort) bool { return self.event.isSet(); } /// Clears the signal. Call it only when nothing waits on it. pub fn reset(self: *Abort) void { self.event.reset(); } /// Returns true when the signal is set, false when the timeout expired or the /// wait was canceled first. pub fn wait(self: *Abort, io: std.Io, timeout: std.Io.Timeout) bool { const deadline = timeout.toDeadline(io); while (true) { self.event.waitTimeout(io, deadline) catch |err| switch (err) { error.Canceled => return self.event.isSet(), // A spurious wakeup also reports a timeout. error.Timeout => if (expired(io, deadline)) { return self.event.isSet(); } else { continue; }, }; return true; } } }; /// Whether `deadline` has passed. It must be `.none`, which never expires, or a /// `.deadline` value from `Timeout.toDeadline`. pub fn expired(io: std.Io, deadline: std.Io.Timeout) bool { std.debug.assert(deadline != .duration); const left = deadline.toDurationFromNow(io) orelse return false; return left.raw.nanoseconds <= 0; } const testing = std.testing; test "a waiter in another task wakes when the signal is set" { var abort: Abort = .{}; var waiter = try testing.io.concurrent(Abort.wait, .{ &abort, testing.io, .{ .duration = .{ .raw = .fromSeconds(30), .clock = .awake } } }); defer _ = waiter.cancel(testing.io); abort.set(testing.io); try testing.expect(waiter.await(testing.io)); } test "a wait times out while the signal is unset, and reset clears the signal" { var abort: Abort = .{}; try testing.expect(!abort.isSet()); try testing.expect(!abort.wait(testing.io, .{ .duration = .{ .raw = .fromMilliseconds(5), .clock = .awake } })); abort.set(testing.io); try testing.expect(abort.isSet()); try testing.expect(abort.wait(testing.io, .{ .duration = .{ .raw = .fromSeconds(30), .clock = .awake } })); abort.reset(); try testing.expect(!abort.isSet()); }