Class: Futuroscope::Future

Inherits:
Delegator
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/futuroscope/future.rb

Overview

A Future is an object that gets initialized with a block and will behave exactly like the block’s result, but being able to “borrow” its result from the future. That is, will block when the result is not ready until it is, and will return it instantly if the thread’s execution already finished.

Instance Method Summary collapse

Constructor Details

#initialize(pool = ::Futuroscope.default_pool, &block) ⇒ Future

Initializes a future with a block and starts its execution.

Examples:

future = Futuroscope::Future.new { sleep(1); :edballs }
sleep(1)
puts future
=> :edballs
# This will return in 1 second and not 2 if the execution wasn't
# deferred to a thread.

pool - A pool where all the futures will be scheduled. block - A block that will be run in the background.

Returns a Future



29
30
31
32
33
34
35
# File 'lib/futuroscope/future.rb', line 29

def initialize(pool = ::Futuroscope.default_pool, &block)
  @queue = ::SizedQueue.new(1)
  @pool = pool
  @block = block
  @mutex = Mutex.new
  @pool.queue self
end

Instance Method Details

#__getobj__Object Also known as: future_value

Semipublic: Returns the future’s value. Will wait for the future to be completed or return its value otherwise. Can be called multiple times.

Returns the Future’s block execution result.



48
49
50
51
52
53
# File 'lib/futuroscope/future.rb', line 48

def __getobj__
  resolved = resolved_future_value

  raise resolved[:exception] if resolved[:exception]
  resolved[:value]
end

#__setobj__(obj) ⇒ Object



55
56
57
# File 'lib/futuroscope/future.rb', line 55

def __setobj__ obj
  @resolved_future = { value: obj }
end

#marshal_dumpObject



59
60
61
# File 'lib/futuroscope/future.rb', line 59

def marshal_dump
  resolved_future_value
end

#marshal_load(value) ⇒ Object



63
64
65
# File 'lib/futuroscope/future.rb', line 63

def marshal_load value
  @resolved_future = value
end

#run_futureObject

Semipublic: Forces this future to be run.



38
39
40
41
42
# File 'lib/futuroscope/future.rb', line 38

def run_future
  @queue.push(value: @block.call)
rescue ::Exception => e
  @queue.push(exception: e)
end