Table of Contents

sync/atomic

What is it?

`sync/atomic` provides low-level atomic memory primitives for safe, lock-free access to shared integer and pointer values.

What is it used for?

When to use

Example: counter

package main
 
import (
    "fmt"
    "sync"
    "sync/atomic"
)
 
func main() {
    var n int64
    var wg sync.WaitGroup
 
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            atomic.AddInt64(&n, 1)
        }()
    }
 
    wg.Wait()
    fmt.Println(atomic.LoadInt64(&n))
}

Notes / pitfalls

Hard words (English)