Skip to content

Commit 630b7cc

Browse files
committed
Add Async::Group for straight forward list of children nodes without an associated task.
1 parent 375bf9b commit 630b7cc

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

lib/async/group.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# frozen_string_literal: true
2+
3+
# Released under the MIT License.
4+
# Copyright, 2019-2022, by Samuel Williams.
5+
6+
require_relative 'list'
7+
require_relative 'task'
8+
9+
module Async
10+
class Group < Node
11+
def initialize(parent = Task.current, **options)
12+
super(parent, **options)
13+
end
14+
15+
# Execute a child task and add it to the barrier.
16+
# @asynchronous Executes the given block concurrently.
17+
def async(*arguments, **options, &block)
18+
task = Task.new(self, **options, &block)
19+
20+
task.run(*arguments)
21+
22+
return task
23+
end
24+
25+
# Wait for all children tasks to finish.
26+
def wait
27+
while !finished?
28+
Fiber.scheduler.yield
29+
end
30+
end
31+
end
32+
end

test/async/group.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# frozen_string_literal: true
2+
3+
# Released under the MIT License.
4+
# Copyright, 2022, by Samuel Williams.
5+
6+
require 'async/group'
7+
require 'sus/fixtures/async'
8+
9+
describe Async::Group do
10+
include Sus::Fixtures::Async::ReactorContext
11+
12+
let(:group) {subject.new}
13+
14+
it 'can wait for all tasks to finish' do
15+
task = group.async do
16+
sleep 0.001
17+
end
18+
19+
expect(task.status).to be == :running
20+
21+
group.wait
22+
23+
expect(task.status).to be == :complete
24+
end
25+
end

0 commit comments

Comments
 (0)