Skip to content

Add a concurrency primitive for waiting for a specific number of tasks to complete. #189

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions lib/async/limited_barrier.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2022, by Samuel Williams.

module Async
# 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}.
class LimitedBarrier
def initialize(parent: nil, finished: Async::Condition.new)
@finished = finished
@done = []

@parent = parent
end

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

def wait_for(count)
while @done.size < count
@finished.wait
end

return @done.shift(count)
end

def wait(count)
wait_for(count).map(&:result)
end
end
end
23 changes: 23 additions & 0 deletions test/async/limited_barrier.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@

require 'async/limited_barrier'
require 'sus/fixtures/async'

describe Async::LimitedBarrier do
include Sus::Fixtures::Async::ReactorContext

let(:limited_barrier) {subject.new}

it "can wait for a subset of tasks" do
3.times do
limited_barrier.async do
sleep(rand * 0.01)
end
end

done = limited_barrier.wait(2)
expect(done.size).to be == 2

done = limited_barrier.wait(1)
expect(done.size).to be == 1
end
end