sync/atomic 库提供了原子操作的支持,原子操作直接有底层CPU硬件支持,因而一般要比基于操作系统API的锁方式效率高些。对于int类型的增减操作有以下api:
// AddInt32 atomically adds delta to *addr and returns the new value.
func AddInt32(addr *int32, delta int32) (new int32)
// AddUint32 atomically adds delta to *addr and returns the new value.
// To subtract a signed positive constant value c from x, do AddUint32(&x, ^uint32(c-1)).
// In particular, to decrement x, do AddUint32(&x, ^uint32(0)).
func AddUint32(addr *uint32, delta uint32) (new uint32)
// AddInt64 atomically adds delta to *addr and returns the new value.
func AddInt64(addr *int64, delta int64) (new int64)
// AddUint64 atomically adds delta to *addr and returns the new value.
// To subtract a signed positive constant value c from x, do AddUint64(&x, ^uint64(c-1)).
// In particular, to decrement x, do AddUint64(&x, ^uint64(0)).
func AddUint64(addr *uint64, delta uint64) (new uint64)
第一个参数是指针类型,第二个参数是操作的值,类型要和第一个指针类型一致,返回值的类型和参数一致。
代码例子:
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var sum uint32 = 0
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
defer wg.Done()
//sum += 1 //1
atomic.AddUint32(&sum, 1) //2
}()
}
wg.Wait()
fmt.Println(sum)
}
使用原子操作返回的结果是50,使用sum+=1,返回的结果不一定是50。