Atomic Counters in Erlang
Our primary mechanism for managing state in Erlang is through message passing between processes. However, there are other options for managing state. Here we’ll look at using Erlang’s built-in support for atomic operations to create atomic counters accessed by multiple processes.
We expect to get exactly 50,000 operations. Had we used a non-atomic integer and incremented it with regular addition, we’d likely get a different number, changing between runs, because the processes would interfere with each other.
To run the program:
In Erlang, we use processes instead of goroutines, and we use the atomics
module for atomic operations. The atomics:new/2
function creates a new atomic counter, atomics:add/3
increments it, and atomics:get/2
reads its value.
Instead of using a WaitGroup, we spawn processes and wait for them to send a message when they’re done. This achieves the same synchronization as the Go example.
Next, we’ll look at other concurrency primitives in Erlang for managing state.