Class: Async::WorkerPool::Promise

Inherits:
Object
  • Object
show all
Defined in:
lib/async/worker_pool.rb

Overview

Execute the given work in a background thread.

Instance Method Summary collapse

Constructor Details

#initialize(work) ⇒ Promise

Create a new promise.



32
33
34
35
36
37
38
39
# File 'lib/async/worker_pool.rb', line 32

def initialize(work)
	@work = work
	@state = :pending
	@value = nil
	@guard = ::Mutex.new
	@condition = ::ConditionVariable.new
	@thread = nil
end

Instance Method Details

#callObject

Execute the work and resolve the promise.



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/async/worker_pool.rb', line 42

def call
	work = nil
	
	@guard.synchronize do
		@thread = ::Thread.current
		
		return unless work = @work
	end
	
	resolve(work.call)
rescue Exception => error
	reject(error)
end

#cancelObject

Cancel the work and raise an exception in the background thread.



77
78
79
80
81
82
83
84
85
# File 'lib/async/worker_pool.rb', line 77

def cancel
	return unless @work
	
	@guard.synchronize do
		@work = nil
		@state = :cancelled
		@thread&.raise(Interrupt)
	end
end

#waitObject

Wait for the work to be done.



90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/async/worker_pool.rb', line 90

def wait
	@guard.synchronize do
		while @state == :pending
			@condition.wait(@guard)
		end
		
		if @state == :failed
			raise @value
		else
			return @value
		end
	end
end