Class: Async::WorkerPool::Promise

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

Instance Method Summary collapse

Constructor Details

#initialize(work) ⇒ Promise

Returns a new instance of Promise.



27
28
29
30
31
32
33
34
# File 'lib/async/worker_pool.rb', line 27

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

Instance Method Details

#callObject



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/async/worker_pool.rb', line 36

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



70
71
72
73
74
75
76
77
78
# File 'lib/async/worker_pool.rb', line 70

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

#waitObject



80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/async/worker_pool.rb', line 80

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