Waitgroups in PureScript
Our example demonstrates how to wait for multiple concurrent tasks to finish using the Aff
monad and the parallel
package in PureScript.
In this PureScript version, we use the Aff
monad to represent asynchronous computations. The worker
function is defined as an Aff
computation that logs its start and end, with a delay in between to simulate work.
Instead of using a WaitGroup, we use the parallel
function from the Control.Parallel
module to run our worker tasks concurrently. The traverse parallel
combination allows us to run a list of Aff
computations in parallel.
The sequential
function is then used to wait for all parallel computations to complete before the main computation finishes.
To run the program, you would typically use the PureScript compiler (purs
) and Node.js:
The order of workers starting up and finishing is likely to be different for each invocation.
Note that this approach inherently handles error propagation through the Aff
monad. If any of the workers were to throw an error, it would be propagated and the main computation would fail.
This example demonstrates how PureScript’s functional approach to concurrency differs from imperative languages, leveraging its type system and monadic structures to handle parallel computations safely and expressively.