class Concurrent::Cancellation

Provides tools for cooperative cancellation. Inspired by <msdn.microsoft.com/en-us/library/dd537607(v=vs.110).aspx>

@example

# Create new cancellation. `cancellation` is used for cancelling, `token` is passed down to
# tasks for cooperative cancellation
cancellation, token = Concurrent::Cancellation.create
Thread.new(token) do |token|
  # Count 1+1 (simulating some other meaningful work) repeatedly
  # until the token is cancelled through cancellation.
  token.loop_until_canceled { 1+1 }
end
sleep 0.1
cancellation.cancel # Stop the thread by cancelling

@!macro warn.edge

Public Class Methods

create(resolvable_future_or_event = Promises.resolvable_event, *resolve_args) click to toggle source

Creates the cancellation object. Returns both the cancellation and the token for convenience. @param [Object] resolve_args resolve_args Arguments which are used when resolve method is called on

resolvable_future_or_event

@param [Promises::Resolvable] resolvable_future_or_event resolvable used to track cancellation.

Can be retrieved by `token.to_future` ot `token.to_event`.

@example

cancellation, token = Concurrent::Cancellation.create

@return [Array(Cancellation, Cancellation::Token)]

# File lib-edge/concurrent/edge/cancellation.rb, line 29
def self.create(resolvable_future_or_event = Promises.resolvable_event, *resolve_args)
  cancellation = new(resolvable_future_or_event, *resolve_args)
  [cancellation, cancellation.token]
end
new(future, *resolve_args) click to toggle source
# File lib-edge/concurrent/edge/cancellation.rb, line 65
def initialize(future, *resolve_args)
  raise ArgumentError, 'future is not Resolvable' unless future.is_a?(Promises::Resolvable)
  @Cancel      = future
  @Token       = Token.new @Cancel.with_hidden_resolvable
  @ResolveArgs = resolve_args
end

Public Instance Methods

cancel(raise_on_repeated_call = true) click to toggle source

Cancel this cancellation. All executions depending on the token will cooperatively stop. @return [true, false] @raise when cancelling for the second tim

# File lib-edge/concurrent/edge/cancellation.rb, line 45
def cancel(raise_on_repeated_call = true)
  !!@Cancel.resolve(*@ResolveArgs, raise_on_repeated_call)
end
canceled?() click to toggle source

Is the cancellation cancelled? @return [true, false]

# File lib-edge/concurrent/edge/cancellation.rb, line 51
def canceled?
  @Cancel.resolved?
end
inspect()
Alias for: to_s
to_s() click to toggle source

Short string representation. @return [String]

Calls superclass method
# File lib-edge/concurrent/edge/cancellation.rb, line 57
def to_s
  format '%s canceled:%s>', super[0..-2], canceled?
end
Also aliased as: inspect
token() click to toggle source

Returns the token associated with the cancellation. @return [Token]

# File lib-edge/concurrent/edge/cancellation.rb, line 38
def token
  @Token
end