Skip to content

Commit

Permalink
Add WaitGroup.wait and WaitGroup#spawn (#14837)
Browse files Browse the repository at this point in the history
This commit allows for usage of WaitGroup in a way that is significantly
more readable.

    WaitGroup.wait do |wg|
      wg.spawn { http.get "/foo" }
      wg.spawn { http.get "/bar" }
    end
  • Loading branch information
jgaskins authored Aug 20, 2024
1 parent 41f75ca commit 1baf3a7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
13 changes: 13 additions & 0 deletions spec/std/wait_group_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,19 @@ describe WaitGroup do
extra.get.should eq(32)
end

it "takes a block to WaitGroup.wait" do
fiber_count = 10
completed = Array.new(fiber_count) { false }

WaitGroup.wait do |wg|
fiber_count.times do |i|
wg.spawn { completed[i] = true }
end
end

completed.should eq [true] * 10
end

# the test takes far too much time for the interpreter to complete
{% unless flag?(:interpreted) %}
it "stress add/done/wait" do
Expand Down
34 changes: 34 additions & 0 deletions src/wait_group.cr
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,46 @@ class WaitGroup
end
end

# Yields a `WaitGroup` instance and waits at the end of the block for all of
# the work enqueued inside it to complete.
#
# ```
# WaitGroup.wait do |wg|
# items.each do |item|
# wg.spawn { process item }
# end
# end
# ```
def self.wait : Nil
instance = new
yield instance
instance.wait
end

def initialize(n : Int32 = 0)
@waiting = Crystal::PointerLinkedList(Waiting).new
@lock = Crystal::SpinLock.new
@counter = Atomic(Int32).new(n)
end

# Increment the counter by 1, perform the work inside the block in a separate
# fiber, decrementing the counter after it completes or raises. Returns the
# `Fiber` that was spawned.
#
# ```
# wg = WaitGroup.new
# wg.spawn { do_something }
# wg.wait
# ```
def spawn(&block) : Fiber
add
::spawn do
block.call
ensure
done
end
end

# Increments the counter by how many fibers we want to wait for.
#
# A negative value decrements the counter. When the counter reaches zero,
Expand Down

0 comments on commit 1baf3a7

Please sign in to comment.