Waitgroups in Erlang
Erlang doesn’t have a direct equivalent to Go’s WaitGroups, but we can achieve similar functionality using processes and message passing. We’ll use the spawn
function to create processes (similar to goroutines) and send messages to coordinate their completion.
To run the program:
In this Erlang version:
We define a
worker/1
function that simulates work by sleeping for a second.The
spawn_and_wait/1
function creates N processes, each running theworker/1
function. Each process sends a message back to the parent when it’s done.The
wait_for_workers/1
function uses recursion to wait for messages from all spawned processes.In the
main/0
function, we callspawn_and_wait(5)
to create and wait for 5 worker processes.
Note that the order of workers starting up and finishing is likely to be different for each invocation, just like in the original example.
Erlang’s built-in concurrency model based on lightweight processes and message passing provides a natural way to handle parallel tasks. While it doesn’t have an exact equivalent to Go’s WaitGroups, the message passing approach allows for flexible coordination of concurrent activities.
For more advanced use cases, you might want to look into OTP (Open Telecom Platform) behaviors like gen_server
or supervisor
, which provide robust patterns for building concurrent and fault-tolerant applications in Erlang.