Waitgroups in Crystal
Our example demonstrates how to wait for multiple fibers to finish using a Channel
. In Crystal, fibers are lightweight concurrent units of execution, similar to goroutines in other languages.
To run the program:
The order of workers starting up and finishing is likely to be different for each invocation.
In this Crystal version:
We use a
Channel
to synchronize the fibers, which is similar to using a WaitGroup in other languages.The
spawn
keyword is used to create new fibers, which are Crystal’s lightweight threads.Instead of explicitly incrementing and decrementing a counter, we send a signal to the channel when each fiber is done.
We wait for all fibers to finish by receiving from the channel once for each fiber we spawned.
Crystal’s
sleep
function is used to simulate work, similar totime.Sleep
in the original example.
This approach achieves the same goal of waiting for multiple concurrent operations to complete before proceeding. However, as noted, it doesn’t provide a built-in way to propagate errors from the workers. For more complex scenarios, you might need to implement additional error handling mechanisms.