Skip to content

原子计数器

https://gobyexample-cn.github.io/atomic-counters

go
package main

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

func main() {

    var ops uint64

    var wg sync.WaitGroup

    for i := 0; i < 50; i++ {
        wg.Add(1)

        // 开了50个goroutine
        go func() {
            for c := 0; c < 1000; c++ {
                // 每次 ops + 1
                atomic.AddUint64(&ops, 1)
                // ops++ // 如果是 ops ++ ,结果可能是 2000多,而不是 5000
            }
            wg.Done()
        }()
    }

    wg.Wait()

    fmt.Println("ops:", ops)
}

原子性(Atomicity),比如两个 goroutine 同时 x++,可能会覆写,即丢失一次 +1。

atomic.AddUint64(&ops, 1) 保证多个 goroutine 同时修改同一个变量时,不发生数据竞争(data race),保证结果正确。

也就类似于锁