Use sync/atomic to perform lock-free, thread-safe operations on specific variable types like int64, uint64, and uintptr without the overhead of sync.Mutex.
package main
import (
"fmt"
"sync/atomic"
)
var counter int64
func main() {
// Atomically add 1 to counter
atomic.AddInt64(&counter, 1)
// Atomically load the current value
val := atomic.LoadInt64(&counter)
fmt.Println(val)
}
Key Functions:
atomic.LoadInt64(addr)/atomic.StoreInt64(addr, val): Read and write values.atomic.AddInt64(addr, delta): Add a value and return the new result.atomic.CompareAndSwapInt64(addr, old, new): Swap only if the current value matchesold.atomic.LoadPointer(addr)/atomic.StorePointer(addr, ptr): For pointers (useunsafe.Pointer).
Important: You must pass the address of the variable (&counter) to these functions. Do not use sync/atomic for complex types like slices or maps; use sync.Mutex or sync.RWMutex for those.