Go Atomics
Similar to
C++ Atomics, Go Atomic operations provide safe, lock-free updates to shared
variables across multiple goroutines. Use CPU-level hardware
instructions instead of heavy OS locks.
Provided by sync/atomic package.
| With Atomic | Without Atomic | |
|---|---|---|
| Thread-safe | Standard Go types are thread safe | Not thread safe |
| functions to work on data | Add(), Load(), Store(), Swap() |
Code
| Code with Atomic (Correct value) | Code without Atomic |
|---|---|
|
|
How Atomic Works at the CPU Hardware Level?
1st check memory layouts of
Process
and
Thread.
Atomic variables are allocated on common area(DS or HS).
Atomic forces the CPU hardware to line up the requests so they execute
one by one at the hardware level.
Go compiler translates that function into special atomic CPU
instructions (like LOCK XADD or CMPXCHG on x86 processors)