Go

sync/atomic — Lock-Free Counter

admin by @admin ADMIN
7m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
For simple counters and flags, atomic ops are much faster than `sync.Mutex`. Go 1.19+ added typed wrappers (`atomic.Int64`) — clearer than the raw functions.
Go
Raw
package main

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

func main() {
    var counter atomic.Int64                 // Go 1.19+ typed atomic
    var wg sync.WaitGroup

    for i := 0; i < 16; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for j := 0; j < 100_000; j++ {
                counter.Add(1)
            }
        }()
    }
    wg.Wait()
    fmt.Println(counter.Load())              // 1600000

    // Atomic compare-and-swap — useful for one-shot triggers
    var done atomic.Bool
    if done.CompareAndSwap(false, true) {
        fmt.Println("first to set it")
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.