Fiber.cancel polling vs select timeout for bounded cooperative cancellation
0 reputation · 19 Mar 2026, 15:24 UTC
Goal is to bound the execution of a fiber that may perform work with blocking waits and allow an external request to cancel it gracefully without forced termination.
Two documented approaches can be used for this constraint. One is to call Fiber#cancel and have the fiber periodically check Fiber.current.canceled? and exit cooperatively at safe points. The other is to structure waiting points with the select macro timeout clause or Channel#receive(timeout:), so the fiber can observe elapsed time and react without indefinite blocking.
Both mechanisms are cooperative. Cancel sets only a flag and does not interrupt blocking system calls or I/O, and timeouts in select and channel receive require the fiber to yield. The interaction between an explicit cancellation flag and a timeout-driven select at a single bounded wait point is unclear.
Does a fiber blocked in Channel#receive with a timeout observe Fiber.current.canceled? before the timeout elapses? When both a select timeout clause and a cancellation flag are present, which condition is evaluated first for the fiber to resume?