===== 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? ==== * Perform simple concurrent operations without using `Mutex`. * Common ops: atomic add, load/store, compare-and-swap (CAS). ==== When to use ==== * You need very simple shared state, like counters, flags, or pointers. * You want to avoid lock overhead for hot paths. * You understand the memory-ordering implications (advanced topic). ==== 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 ==== * Prefer `sync.Mutex` for complex shared state (maps, slices, structs with multiple fields). * For correctness, always use `atomic.Load*` / `atomic.Store*` instead of plain reads/writes. * Do not mix atomic and non-atomic access to the same variable. ==== Related ==== * [[go:concurrency:mutex|sync.Mutex]] * [[go:concurrency:rwmutex|sync.RWMutex]] * [[go:concurrency:race_detector|Race detector (-race)]] ==== Hard words (English) ==== * **lock-free** /ˌlɑːk ˈfriː/: không cần khóa * **atomic** /əˈtɑːmɪk/: nguyên tử (trọn vẹn, không bị xen ngang) * **primitive** /ˈprɪmətɪv/: thao tác/công cụ nền tảng * **overhead** /ˈoʊvərhed/: chi phí phát sinh * **hot path** /hɑːt pæθ/: đoạn code chạy rất thường xuyên * **implication** /ˌɪmplɪˈkeɪʃən/: hệ quả * **memory ordering** /ˈmeməri ˈɔːrdərɪŋ/: thứ tự bộ nhớ (khái niệm nâng cao) * **compare-and-swap (CAS)** /kəmˈper ænd swɑːp/: so sánh và hoán đổi