lib/thread/promise.rb in thread-0.0.4.1 vs lib/thread/promise.rb in thread-0.0.4.2
- old
+ new
@@ -13,11 +13,10 @@
# A promise is an object that lets you wait for a value to be delivered to it.
class Thread::Promise
# Create a promise.
def initialize
@mutex = Mutex.new
- @cond = ConditionVariable.new
end
# Check if a value has been delivered.
def delivered?
@mutex.synchronize {
@@ -31,30 +30,43 @@
def deliver (value)
return if delivered?
@mutex.synchronize {
@value = value
- @cond.broadcast
+
+ cond.broadcast if cond?
}
self
end
alias << deliver
# Get the value that's been delivered, if none has been delivered yet the call
# will block until one is delivered.
+ #
+ # An optional timeout can be passed which will return nil if nothing has been
+ # delivered.
def value (timeout = nil)
return @value if delivered?
@mutex.synchronize {
- @cond.wait(@mutex, *timeout)
+ cond.wait(@mutex, *timeout)
}
return @value if delivered?
end
alias ~ value
+
+private
+ def cond?
+ instance_variable_defined? :@cond
+ end
+
+ def cond
+ @cond ||= ConditionVariable.new
+ end
end
module Kernel
def promise
Thread::Promise.new