From 8cc506030f3b20ef1d8b85e7f86e07c2eeb042b7 Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Thu, 16 Jan 2025 21:02:53 +1300 Subject: [PATCH] Add support for `Scheduler#fiber_interrupt`. --- lib/async/scheduler.rb | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/lib/async/scheduler.rb b/lib/async/scheduler.rb index 56c9620b..9cbe3938 100644 --- a/lib/async/scheduler.rb +++ b/lib/async/scheduler.rb @@ -347,6 +347,32 @@ def io_write(io, buffer, length, offset = 0) end end + # Used to defer stopping the current task until later. + class RaiseException + # Create a new stop later operation. + # + # @parameter task [Task] The task to stop later. + def initialize(fiber, exception) + @fiber = fiber + @exception = exception + end + + # @returns [Boolean] Whether the task is alive. + def alive? + @fiber.alive? + end + + # Transfer control to the operation - this will stop the task. + def transfer + @fiber.raise(@exception) + end + end + + # Raise an exception on the specified fiber, waking up the event loop if necessary. + def fiber_interrupt(fiber, exception) + unblock(nil, RaiseException.new(fiber, exception)) + end + # Wait for the specified process ID to exit. # # @public Since *Async v2*.