This is a [MICRO WRITEUP]
Both of them provide the ability to protect shared data from concurrent access or being overwritten while a single goroutine is processing it. However, there are several use cases for sync.atomic. But in most cases, just use sync.Mutex and it works fine with little overhead. You only need sync.atomic when dealing with high-frequency trading or kernel-level code where every bit of performance matters.
This is from “The golang Memory Model”
](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Futt8ufa431kpd9qd9cbp.png)
sync/atomic uses hardware level optimization by using CPU instructions to lock individual data from being accessed concurrently. On x86 processors, it uses the LOCK instruction; on ARM, it uses LDAR/STLR. Because it locks the entire cache line so no other CPU core can access it, it’s not cache friendly. Even if it bypasses the OS kernel to avoid putting goroutines to sleep, it introduces other low level rabbit holes and an unmaintainable nightmare that can drive you and other maintainers crazy when you’re just trying to write a simple HTTP server, like the golang memory model said, Dont be clever.
That said, sync/atomic is fine for the simple stuff, like a single counter or a flag that one goroutine sets and the others read (atomic.Int64, atomic.Bool). But the moment two variables have to change together and stay consistent with each other, atomic can’t help you. Each operation is atomic on its own, but the group of them is not, and that’s exactly the job of sync.Mutex.
