Class: QuackConcurrency::Future
- Inherits:
-
Object
- Object
- QuackConcurrency::Future
- Defined in:
- lib/quack_concurrency/future.rb,
lib/quack_concurrency/future/canceled.rb,
lib/quack_concurrency/future/complete.rb
Overview
Used to send a value or error from one thread to another without the need for coordination.
Defined Under Namespace
Instance Method Summary collapse
-
#cancel(exception = nil) ⇒ void
Cancels it.
-
#complete? ⇒ Boolean
Checks if it has a value or error set.
-
#get ⇒ Object
Gets it’s value.
-
#initialize ⇒ Future
constructor
Creates a new Future concurrency tool.
-
#raise(exception = nil) ⇒ void
Sets it to an error.
-
#set(new_value = nil) ⇒ void
Sets it to a value.
Constructor Details
#initialize ⇒ Future
Creates a new QuackConcurrency::Future concurrency tool.
8 9 10 11 12 13 14 |
# File 'lib/quack_concurrency/future.rb', line 8 def initialize @complete = false @exception = false @mutex = ::Mutex.new @value = nil @waiter = Waiter.new end |
Instance Method Details
#cancel(exception = nil) ⇒ void
This method returns an undefined value.
Cancels it. If no exception
is specified, a Canceled error will be set.
21 22 23 24 25 |
# File 'lib/quack_concurrency/future.rb', line 21 def cancel(exception = nil) exception ||= Canceled.new self.raise(exception) nil end |
#complete? ⇒ Boolean
Checks if it has a value or error set.
29 30 31 |
# File 'lib/quack_concurrency/future.rb', line 29 def complete? @complete end |
#get ⇒ Object
Note:
This method will block until the future has completed
Gets it’s value.
38 39 40 41 42 |
# File 'lib/quack_concurrency/future.rb', line 38 def get @waiter.wait Kernel.raise(@exception) if @exception @value end |
#raise(exception = nil) ⇒ void
This method returns an undefined value.
Sets it to an error.
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/quack_concurrency/future.rb', line 48 def raise(exception = nil) exception = case when exception == nil then StandardError.new when exception.is_a?(Exception) then exception when Exception >= exception then exception.new else Kernel.raise(TypeError, "'exception' must be nil or an instance of or descendant of Exception") end @mutex.synchronize do Kernel.raise(Complete) if @complete @complete = true @exception = exception @waiter.resume_all_indefinitely end nil end |
#set(new_value = nil) ⇒ void
This method returns an undefined value.
Sets it to a value.
69 70 71 72 73 74 75 76 77 |
# File 'lib/quack_concurrency/future.rb', line 69 def set(new_value = nil) @mutex.synchronize do Kernel.raise(Complete) if @complete @complete = true @value = new_value @waiter.resume_all_indefinitely end nil end |