package main import ( "fmt" "sync/atomic" ) /* 用原子来替换锁,其主要原因是: 原子操作由底层硬件支持,而锁则由操作系统提供的API实现 若实现相同功能,原子操作通常会更有效率 */ func main() { var a int64 = 123 //保证将456赋值到a的地址中(期间a一定不会被其他人访问) atomic.StoreInt64(&a, 456) fmt.Println(a) //456 a = 123 new := atomic.AddInt64(&a, 2) fmt.Println(a, new) //125 125 a = 123 old := atomic.SwapInt64(&a, 456) fmt.Println(old, a) //123 456 a = 123 swapped := atomic.CompareAndSwapInt64(&a, 123, 456) fmt.Println(swapped, a) //true 456 /*模拟a被并发修改了*/ a = 321 //确保a(原值123)在没有并发修改的情况下被重新赋值为456 swapped = atomic.CompareAndSwapInt64(&a, 123, 456) fmt.Println(swapped, a) //false 321 }
输出:
456 125 125 123 456 true 456 false 321