Besides a `sync.Mutex`, what is another common and often more performant way to handle a simple shared numeric counter in Go?

Go & Rust interview question for Advanced practice.

Answer

Using the sync/atomic package for lock-free operations.

Explanation

The sync/atomic package provides low-level atomic memory primitives that allow for safe, lock-free concurrent access to simple data types like integers. For a simple operation like incrementing a counter, atomic.AddInt64(&counter, 1) is often more performant than using a mutex because it does not involve the overhead of locking and unlocking.

Related Questions