Atomic Counters in Crystal
Our primary mechanism for managing state in Crystal is communication over channels. However, there are a few other options for managing state. Here we’ll look at using atomic operations for atomic counters accessed by multiple fibers.
We expect to get exactly 50,000 operations. Had we used a non-atomic integer and incremented it with ops += 1
, we’d likely get a different number, changing between runs, because the fibers would interfere with each other.
In Crystal, we use Atomic
types from the atomic
module to achieve atomic operations. The spawn
keyword is used to create fibers (lightweight threads) which are similar to goroutines in Go. Instead of using a WaitGroup
, we use a Channel
to synchronize the completion of fibers.
The Atomic
class provides methods like add
and get
for atomic operations, which are similar to the Add
and Load
methods in Go’s atomic
package.
Next, we’ll look at mutexes, another tool for managing state.