class Garcon::Future

Public Class Methods

execute(opts = {}, &block) click to toggle source

Create a new ‘Future` object with the given block, execute it, and return the `:pending` object.

@example

future = Garcon::Future.execute{ sleep(1); 42 }
future.state #=> :pending

@yield the asynchronous operation to perform.

@!macro executor_and_deref_options.

@option opts [object, Array] :args

Zero or more arguments to be passed the task block on execution.

@raise [ArgumentError] if no block is given.

@return [Future]

The newly created `Future` in the `:pending` state.
# File lib/garcon/task/future.rb, line 93
def self.execute(opts = {}, &block)
  Future.new(opts, &block).execute
end
new(opts = {}, &block) click to toggle source

Create a new ‘Future` in the `:unscheduled` state.

@yield the asynchronous operation to perform

@!macro executor_and_deref_options

@option opts [object, Array] :args

Zero or more arguments to be passed the task block on execution.

@raise [ArgumentError] if no block is given

Calls superclass method
# File lib/garcon/task/future.rb, line 42
def initialize(opts = {}, &block)
  raise ArgumentError.new('no block given') unless block_given?
  super(IVar::NO_VALUE, opts)
  @state    = :unscheduled
  @task     = block
  @executor = get_executor_from(opts) || Garcon.global_io_executor
  @args     = get_arguments_from(opts)
end

Public Instance Methods

execute() click to toggle source

Execute an ‘:unscheduled` `Future`. Immediately sets the state to `:pending` and passes the block to a new thread/thread pool for eventual execution. Does nothing if the `Future` is in any state other than `:unscheduled`.

@return [Future] a reference to ‘self`

@example Instance and execute in separate steps

future = Garcon::Future.new{ sleep(1); 42 }
future.state #=> :unscheduled
future.execute
future.state #=> :pending

@example Instance and execute in one line

future = Garcon::Future.new{ sleep(1); 42 }.execute
future.state #=> :pending
# File lib/garcon/task/future.rb, line 67
def execute
  if compare_and_set_state(:pending, :unscheduled)
    @executor.post(@args){ work }
    self
  end
end