Waitgroups in Elixir
To wait for multiple processes to finish in Elixir, we can use a concept similar to wait groups called Task.async_stream/3
combined with Enum.to_list/1
.
This is the function we’ll run in every process:
In the main
function:
We use Task.async_stream/3
to launch several processes. This function automatically manages the concurrency and waiting for all processes to finish.
The Enum.to_list/1
call at the end ensures that we wait for all tasks to complete before moving on.
To run the program:
The order of workers starting up and finishing is likely to be different for each invocation.
Note that this approach in Elixir automatically handles errors and terminates all tasks if any of them fail. For more advanced use cases, you might want to look into the Task
module and OTP behaviors like GenServer
.