From 0df552cc9e9827966872e65b59ad076293550c8b Mon Sep 17 00:00:00 2001 From: Trevor Turk Date: Mon, 5 Dec 2022 15:20:06 -0600 Subject: [PATCH] Add guides about barriers with a fan out and termination --- guides/asynchronous-tasks/readme.md | 40 +++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/guides/asynchronous-tasks/readme.md b/guides/asynchronous-tasks/readme.md index 3915b61a..4b1f0196 100644 --- a/guides/asynchronous-tasks/readme.md +++ b/guides/asynchronous-tasks/readme.md @@ -200,6 +200,46 @@ Async do end ``` +### Stopping all Tasks held in a Barrier + +To stop (terminate/cancel) the all tasks held in a barrier: + +```ruby +barrier = Async::Barrier.new + +Async do + tasks = 3.times.map do |i| + barrier.async do + sleep 1 + puts "Hello World #{i}" + end + end + + barrier.stop +end +``` + +If you're letting individual tasks held by a barrier throw unhandled exceptions, be sure to call ({ruby Async::Barrier#stop}): + +```ruby +barrier = Async::Barrier.new + +Async do + tasks = 3.times.map do |i| + barrier.async do + sleep 1 + puts "Hello World #{i}" + end + end + + begin + barrier.wait + ensure + barrier.stop + end +end +``` + ## Resource Management In order to ensure your resources are cleaned up correctly, make sure you wrap resources appropriately, e.g.: