CodeNebula
Go⚡Concurrencyintermediate

sync/atomic

Go · Concurrency · Run with go run

Explanation

The `sync/atomic` package provides lock-free, hardware-atomic operations on primitive types (`int32`, `int64`, `uint64`, `Pointer`, etc.). Atomic operations are faster than mutexes for simple counters or flags because they use CPU instructions (CAS, fetch-and-add) rather than OS-level locking.

Real-World Scenario

A metrics collector increments a request counter from thousands of goroutines. Using `atomic.AddInt64(&requests, 1)` is 3–10× faster than a mutex-protected increment and avoids contention.

Quick Snippet

snippet.go
import "sync/atomic"

var requests atomic.Int64 // zero value is valid

func handleRequest() {
    requests.Add(1)
    // ... handle request
}

func stats() {
    fmt.Printf("Total requests: %d\n", requests.Load())
}

// Atomic compare-and-swap (CAS) — update only if current value matches expected
var flag atomic.Bool
if flag.CompareAndSwap(false, true) {
    fmt.Println("acquired flag")
}

Full Example

atomic.go
// Compile: go run atomic.go
// Output:
//   total requests: 5000
//   flag acquired once: true
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	var requests atomic.Int64

	var wg sync.WaitGroup
	for i := 0; i < 5000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			requests.Add(1)
		}()
	}
	wg.Wait()
	fmt.Println("total requests:", requests.Load())

	// Compare-and-swap — only the first caller succeeds
	var flag atomic.Bool
	acquired := flag.CompareAndSwap(false, true)
	fmt.Println("flag acquired once:", acquired)
}
Run command
go run atomic.go