Stateful Goroutines in Elixir
Our example demonstrates how to manage state using processes in Elixir. This approach aligns with Elixir’s philosophy of using message passing for communication between concurrent processes.
In this example, we use a single process to manage the state, which guarantees that the data is never corrupted with concurrent access. Other processes send messages to the state-owning process to read or write data.
The StatefulProcess
module defines the state-owning process. It uses a loop function that receives messages for reading and writing data. The read/2
and write/3
functions are used to send messages to this process and wait for the response.
In the Main
module, we start 100 processes that continuously read from the state, and 10 processes that write to the state. We use spawn/1
to create these processes, which is similar to starting goroutines in Go.
After letting the processes run for a second, we print out the final state.
Running this program will show the final state of the map after all the concurrent reads and writes:
This Elixir version demonstrates how to achieve similar functionality to the Go example, using Elixir’s built-in concurrency primitives. The approach aligns with Elixir’s philosophy of sharing data by sending messages between processes, rather than sharing memory directly.