class Futuroscope::Future
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.
Public Class Methods
new(pool = ::Futuroscope.default_pool, &block)
click to toggle source
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
# 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
Public Instance Methods
__getobj__()
click to toggle source
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.
# File lib/futuroscope/future.rb, line 48 def __getobj__ resolved_future_value_or_raise[:value] end
Also aliased as: future_value
__setobj__(obj)
click to toggle source
# File lib/futuroscope/future.rb, line 52 def __setobj__ obj @resolved_future = { value: obj } end
marshal_dump()
click to toggle source
# File lib/futuroscope/future.rb, line 56 def marshal_dump resolved_future_value_or_raise end
marshal_load(value)
click to toggle source
# File lib/futuroscope/future.rb, line 60 def marshal_load value @resolved_future = value end
run_future()
click to toggle source
Semipublic: Forces this future to be run.
# File lib/futuroscope/future.rb, line 38 def run_future @queue.push(value: @block.call) rescue ::Exception => e @queue.push(exception: e) end
Private Instance Methods
resolved_future_value()
click to toggle source
# File lib/futuroscope/future.rb, line 77 def resolved_future_value @resolved_future || @mutex.synchronize do @resolved_future ||= @queue.pop end end
resolved_future_value_or_raise()
click to toggle source
# File lib/futuroscope/future.rb, line 70 def resolved_future_value_or_raise resolved = resolved_future_value Kernel.raise resolved[:exception] if resolved[:exception] resolved end