Class: Thread::Promise

Inherits:
Object
  • Object
show all
Defined in:
lib/thread/promise.rb

Overview

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

Instance Method Summary collapse

Constructor Details

#initializePromise

Create a promise.



16
17
18
# File 'lib/thread/promise.rb', line 16

def initialize
	@mutex = Mutex.new
end

Instance Method Details

#deliver(value) ⇒ Object Also known as: <<

Deliver a value.



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/thread/promise.rb', line 30

def deliver (value)
	return self if delivered?

	@mutex.synchronize {
		@value = value

		cond.broadcast if cond?
	}

	self
end

#delivered?Boolean Also known as: realized?

Check if a value has been delivered.

Returns:

  • (Boolean)


21
22
23
24
25
# File 'lib/thread/promise.rb', line 21

def delivered?
	@mutex.synchronize {
		instance_variable_defined? :@value
	}
end

#value(timeout = nil) ⇒ Object Also known as: ~

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.



49
50
51
52
53
54
55
56
57
# 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