Class: Futuroscope::Future
- Inherits:
-
Delegator
- Object
- Delegator
- Futuroscope::Future
- 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
-
#__getobj__ ⇒ Object
Semipublic: Returns the future’s value.
-
#initialize(pool = ::Futuroscope.default_pool, &block) ⇒ Future
constructor
Initializes a future with a block and starts its execution.
-
#run_future ⇒ Object
Semipublic: Forces this future to be run.
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
28 29 30 31 32 33 |
# File 'lib/futuroscope/future.rb', line 28 def initialize(pool = ::Futuroscope.default_pool, &block) @queue = ::SizedQueue.new(1) @pool = pool @block = block @pool.queue self end |
Instance Method Details
#__getobj__ ⇒ Object
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.
46 47 48 49 50 51 |
# File 'lib/futuroscope/future.rb', line 46 def __getobj__ resolved = resolved_future_value raise resolved[:exception] if resolved[:exception] resolved[:value] end |
#run_future ⇒ Object
Semipublic: Forces this future to be run.
36 37 38 39 40 |
# File 'lib/futuroscope/future.rb', line 36 def run_future @queue.push(value: @block.call) rescue ::Exception => e @queue.push(exception: e) end |