Class: Rclrb::Future
- Inherits:
-
Object
- Object
- Rclrb::Future
- Defined in:
- lib/rclrb/future.rb
Overview
Define a future
Class Method Summary collapse
-
.execute(&block) ⇒ Object
Execute the block in a thread and return a Future.
Instance Method Summary collapse
-
#add_observer(&block) ⇒ Object
Add an observer, which is executed once the result is set.
-
#has_result? ⇒ Boolean
Returns true if it already has a result.
-
#initialize ⇒ Future
constructor
Create a future with a nil result.
-
#result ⇒ Object
Wait for the result and return it.
-
#set_exception(ex) ⇒ Object
Set that an exception occurs.
-
#set_result(result) ⇒ Object
Set the result of the future.
-
#wait_for_result ⇒ Object
Wait undefinitely for a result.
Constructor Details
#initialize ⇒ Future
Create a future with a nil result
9 10 11 12 13 14 15 |
# File 'lib/rclrb/future.rb', line 9 def initialize @result = nil @observers = [] @mutex = Mutex.new @resource = ConditionVariable.new @exception = nil end |
Class Method Details
.execute(&block) ⇒ Object
Execute the block in a thread and return a Future. The block is expected to return a value which is set using set_value.
19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/rclrb/future.rb', line 19 def Future.execute(&block) f = Future.new Thread.new do begin f.set_result block.call rescue => ex f.set_exception ex end end return f end |
Instance Method Details
#add_observer(&block) ⇒ Object
Add an observer, which is executed once the result is set.
32 33 34 35 36 37 38 39 40 |
# File 'lib/rclrb/future.rb', line 32 def add_observer(&block) @mutex.synchronize do if @result.nil? @observers.push block else block.call @result end end end |
#has_result? ⇒ Boolean
Returns true if it already has a result.
53 54 55 |
# File 'lib/rclrb/future.rb', line 53 def has_result? return not(@result.nil?) end |
#result ⇒ Object
Wait for the result and return it
77 78 79 80 |
# File 'lib/rclrb/future.rb', line 77 def result() wait_for_result() return @result end |
#set_exception(ex) ⇒ Object
Set that an exception occurs
58 59 60 61 62 63 |
# File 'lib/rclrb/future.rb', line 58 def set_exception(ex) @mutex.synchronize do @exception = ex @resource.signal end end |
#set_result(result) ⇒ Object
Set the result of the future
66 67 68 69 70 71 72 73 74 |
# File 'lib/rclrb/future.rb', line 66 def set_result(result) raise RclError.new "Result is already set" unless @result.nil? @mutex.synchronize do @result = result @resource.signal end @observers.each() { |o| o.call Time.now, @result } @observers = [] end |
#wait_for_result ⇒ Object
Wait undefinitely for a result.
43 44 45 46 47 48 49 50 |
# File 'lib/rclrb/future.rb', line 43 def wait_for_result() @mutex.synchronize do while @result.nil? raise @exception unless @exception.nil? @resource.wait(@mutex) end end end |