Atomic Counters in Rust
Our primary mechanism for managing state in Rust is through ownership and borrowing. However, there are situations where we need to share state across multiple threads. In this example, we’ll look at using atomic operations for concurrent counters accessed by multiple threads.
To run the program:
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 threads would interfere with each other. Moreover, Rust’s ownership system would prevent us from sharing a non-atomic value between threads without proper synchronization.
In Rust, we use Arc
(Atomic Reference Counting) to share the atomic counter across multiple threads. The AtomicU64
type provides atomic operations, and we use fetch_add
for atomic increments. The Ordering::SeqCst
parameter specifies the memory ordering guarantee for the atomic operations.
Next, we’ll look at mutexes, another tool for managing state across threads.