Mutexes in PureScript
In the previous example, we saw how to manage simple counter state using atomic operations. For more complex state, we can use a Ref
to safely access data across multiple fibers.
We’ll create a Container
type that holds a map of counters. Since we want to update it concurrently from multiple fibers, we’ll use a Ref
to synchronize access.
The inc
function uses Ref.modify_
to safely update the counter. This ensures that updates are atomic and thread-safe.
In the main
function, we create a new Container
and define a doIncrement
function that increments a named counter multiple times. We then run three fibers concurrently using parallel
, two of which access the same counter.
Running the program shows that the counters are updated as expected:
This example demonstrates how to use Ref
in PureScript to manage shared state across multiple fibers. While PureScript doesn’t have built-in mutexes like some other languages, the Ref
type provides a safe way to handle concurrent access to mutable state.
Next, we’ll look at implementing this same state management task using only fibers and channels.