class Promise
Execute the given work in a background thread.
Definitions
def initialize(work)
Create a new promise.
Signature
-
parameter
work
Proc
The work to be done.
Implementation
def initialize(work)
@work = work
@state = :pending
@value = nil
@guard = ::Mutex.new
@condition = ::ConditionVariable.new
@thread = nil
end
def call
Execute the work and resolve the promise.
Implementation
def call
work = nil
@guard.synchronize do
@thread = ::Thread.current
return unless work = @work
end
resolve(work.call)
rescue Exception => error
reject(error)
end
def cancel
Cancel the work and raise an exception in the background thread.
Implementation
def cancel
return unless @work
@guard.synchronize do
@work = nil
@state = :cancelled
@thread&.raise(Interrupt)
end
end
def wait
Wait for the work to be done.
Signature
-
returns
Object
The result of the work.
Implementation
def wait
@guard.synchronize do
while @state == :pending
@condition.wait(@guard)
end
if @state == :failed
raise @value
else
return @value
end
end
end