class LittleGhost::Support::CancellationToken
CancellationToken lets related work stop cooperatively without killing its calling thread. Child tokens make cancellation flow through a run’s tree of work.
Cancellation is idempotent and flows only downward. Long-running extensions should call raise_if_cancelled! at bounded intervals.
Public Class Methods
Source
# File lib/little_ghost/support/cancellation_token.rb, line 13 def initialize(parent: nil) @cancelled = false @mutex = Mutex.new @condition = ConditionVariable.new @children = {} @parent = parent parent&.send(:attach, self) end
Optionally attaches this token to parent.
Public Instance Methods
Source
# File lib/little_ghost/support/cancellation_token.rb, line 26 def cancel parent, children = @mutex.synchronize do return self if @cancelled @cancelled = true @condition.broadcast parent = @parent @parent = nil children = @children.keys @children.clear [parent, children] end parent&.send(:detach, self) children.each(&:cancel) self end
Cancels this token and all currently attached children.
Source
# File lib/little_ghost/support/cancellation_token.rb, line 44 def cancelled? @mutex.synchronize { @cancelled } end
Indicates whether cancellation has been requested.
Source
# File lib/little_ghost/support/cancellation_token.rb, line 23 def child = self.class.new(parent: self)
Creates a child cancelled automatically with this token.
Source
# File lib/little_ghost/support/cancellation_token.rb, line 49 def raise_if_cancelled! raise CancelledError, "The run was cancelled" if cancelled? end
Raises CancelledError when cancellation has been requested.
Source
# File lib/little_ghost/support/cancellation_token.rb, line 54 def wait(timeout) deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + Float(timeout) @mutex.synchronize do until @cancelled remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) break unless remaining.positive? @condition.wait(@mutex, remaining) end @cancelled end end
Waits up to timeout seconds for cancellation.