Class: Async::Waiter

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

Overview

A composable synchronization primitive, which allows one task to wait for a number of other tasks to complete. It can be used in conjunction with Semaphore and/or Barrier.

Instance Method Summary collapse

Constructor Details

#initialize(parent: nil, finished: Async::Condition.new) ⇒ Waiter

Returns a new instance of Waiter.



9
10
11
12
13
14
# File 'lib/async/waiter.rb', line 9

def initialize(parent: nil, finished: Async::Condition.new)
	@finished = finished
	@done = []
	
	@parent = parent
end

Instance Method Details

#async(parent: (@parent or Task.current), &block) ⇒ Object

Execute a child task and add it to the waiter.



18
19
20
21
22
23
24
25
# File 'lib/async/waiter.rb', line 18

def async(parent: (@parent or Task.current), &block)
	parent.async do |task|
		yield(task)
	ensure
		@done << task
		@finished.signal
	end
end

#first(count = nil) ⇒ Object

Wait for the first ‘count` tasks to complete.



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

def first(count = nil)
	minimum = count || 1
	
	while @done.size < minimum
		@finished.wait
	end
	
	return @done.shift(*count)
end

#wait(count = nil) ⇒ Object

Wait for the first ‘count` tasks to complete.



43
44
45
46
47
48
49
# File 'lib/async/waiter.rb', line 43

def wait(count = nil)
	if count
		first(count).map(&:wait)
	else
		first.wait
	end
end