x = atomic.AddUint64(&x, 1)
形式的赋值语句。
这样的操作非原子的,这是 sync/atomic
API 中的常见误用。 要使其原子化,请删除赋值并直接调用它,如 atomic.AddUint64(& x, 1)
。 在这种情况下,x
的值由地址原子更新。
示例:
import (
"sync/atomic"
)
type Counter uint64
func AtomicTests() {
x := uint64(1)
x = atomic.AddUint64(&x, 1) // 错误 “直接赋值给原子值”
_, x = 10, atomic.AddUint64(&x, 1) // 错误 “直接赋值给原子值”
x, _ = atomic.AddUint64(&x, 1), 10 // 错误 “直接赋值给原子值”
}