Class: Async::Barrier

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

Overview

A general purpose synchronisation primitive, which allows one task to wait for a number of other tasks to complete. It can be used in conjunction with Semaphore.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent: nil) ⇒ Barrier

Initialize the barrier.



17
18
19
20
21
# File 'lib/async/barrier.rb', line 17

def initialize(parent: nil)
	@tasks = List.new
	
	@parent = parent
end

Instance Attribute Details

#tasksObject (readonly)

All tasks which have been invoked into the barrier.



39
40
41
# File 'lib/async/barrier.rb', line 39

def tasks
  @tasks
end

Instance Method Details

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

Execute a child task and add it to the barrier.



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

def async(*arguments, parent: (@parent or Task.current), **options, &block)
	task = parent.async(*arguments, **options, &block)
	
	@tasks.append(TaskNode.new(task))
	
	return task
end

#empty?Boolean

Whether there are any tasks being held by the barrier.

Returns:

  • (Boolean)


53
54
55
# File 'lib/async/barrier.rb', line 53

def empty?
	@tasks.empty?
end

#sizeObject

Number of tasks being held by the barrier.



34
35
36
# File 'lib/async/barrier.rb', line 34

def size
	@tasks.size
end

#stopObject

Stop all tasks held by the barrier.



72
73
74
75
76
# File 'lib/async/barrier.rb', line 72

def stop
	@tasks.each do |waiting|
		waiting.task.stop
	end
end

#waitObject

Wait for all tasks to complete by invoking Task#wait on each waiting task, which may raise an error. As long as the task has completed, it will be removed from the barrier.



59
60
61
62
63
64
65
66
67
68
# File 'lib/async/barrier.rb', line 59

def wait
	@tasks.each do |waiting|
		task = waiting.task
		begin
			task.wait
		ensure
			@tasks.remove?(waiting) unless task.alive?
		end
	end
end