Skip to content

Commit d897c4d

Browse files
authored
Add guides about barriers with a fan out and termination (#205)
1 parent d06e3de commit d897c4d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

guides/asynchronous-tasks/readme.md

+40
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,46 @@ Async do
200200
end
201201
```
202202

203+
### Stopping all Tasks held in a Barrier
204+
205+
To stop (terminate/cancel) the all tasks held in a barrier:
206+
207+
```ruby
208+
barrier = Async::Barrier.new
209+
210+
Async do
211+
tasks = 3.times.map do |i|
212+
barrier.async do
213+
sleep 1
214+
puts "Hello World #{i}"
215+
end
216+
end
217+
218+
barrier.stop
219+
end
220+
```
221+
222+
If you're letting individual tasks held by a barrier throw unhandled exceptions, be sure to call ({ruby Async::Barrier#stop}):
223+
224+
```ruby
225+
barrier = Async::Barrier.new
226+
227+
Async do
228+
tasks = 3.times.map do |i|
229+
barrier.async do
230+
sleep 1
231+
puts "Hello World #{i}"
232+
end
233+
end
234+
235+
begin
236+
barrier.wait
237+
ensure
238+
barrier.stop
239+
end
240+
end
241+
```
242+
203243
## Resource Management
204244

205245
In order to ensure your resources are cleaned up correctly, make sure you wrap resources appropriately, e.g.:

0 commit comments

Comments
 (0)