Mutexes in Elixir
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 processes.
In this Elixir version, we use a GenServer
to manage shared state, which is analogous to using a mutex in Go. The Container
module implements the GenServer
behavior, providing a way to safely access and modify the counters from multiple processes.
The Container
module defines two main operations:
inc/2
: Increments a named counterget_counters/0
: Retrieves the current state of all counters
In the Main
module, we create a Container
process and spawn three tasks that concurrently increment the counters. We use Task.async/1
to create these concurrent tasks, which is similar to using goroutines in Go.
After all tasks complete, we retrieve and print the final state of the counters.
Running the program shows that the counters are updated as expected:
This example demonstrates how to use Elixir’s built-in concurrency primitives to safely manage shared state across multiple processes. While Elixir encourages a more functional and message-passing oriented approach to concurrency, this example shows how you can achieve mutex-like behavior when needed.
Next, we’ll look at implementing this same state management task using only processes and message passing, which is more idiomatic in Elixir.