In the previous example, we saw how to manage simple counter state using atomic operations. For more complex state, we can use a mutex to safely access data across multiple threads.
Running the program shows that the counters updated as expected.
In this Idris version, we use MVar for mutual exclusion, which is similar to a mutex. We also use IORef for mutable references, as Idris doesn’t have mutable variables by default. The Container is implemented as a record containing an MVar for synchronization and an IORef for the mutable map of counters.
The inc function now takes and releases the MVar explicitly, using a finally block to ensure the MVar is always released, even if an exception occurs.
In the main function, we create threads using forkIO instead of goroutines. Note that Idris doesn’t have a built-in way to wait for threads to complete, so we use a simple threadDelay as a placeholder. In a real application, you’d want to use a proper synchronization mechanism.
This example demonstrates how to use mutexes (via MVar) to safely access shared state across multiple threads in Idris.