class Thread::Promise

A promise is an object that lets you wait for a value to be delivered to it.

Public Class Methods

new() click to toggle source

Create a promise.

# File lib/thread/promise.rb, line 16
def initialize
        @mutex = Mutex.new
end

Public Instance Methods

<<(value)
Alias for: deliver
deliver(value) click to toggle source

Deliver a value.

# File lib/thread/promise.rb, line 30
def deliver(value)
        return self if delivered?

        @mutex.synchronize {
                @value = value

                cond.broadcast if cond?
        }

        self
end
Also aliased as: <<
delivered?() click to toggle source

Check if a value has been delivered.

# File lib/thread/promise.rb, line 21
def delivered?
        @mutex.synchronize {
                instance_variable_defined? :@value
        }
end
Also aliased as: realized?
realized?()
Alias for: delivered?
value(timeout = nil) click to toggle source

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.

# File lib/thread/promise.rb, line 49
def value(timeout = nil)
        return @value if delivered?

        @mutex.synchronize {
                cond.wait(@mutex, *timeout)
        }

        return @value if delivered?
end
Also aliased as: ~
~(timeout = nil)
Alias for: value

Private Instance Methods

cond() click to toggle source
# File lib/thread/promise.rb, line 66
def cond
        @cond ||= ConditionVariable.new
end
cond?() click to toggle source
# File lib/thread/promise.rb, line 62
def cond?
        instance_variable_defined? :@cond
end