[TOC] > [参考](https://mp.weixin.qq.com/s?__biz=MzAxMTA4Njc0OQ==&mid=2651438345&idx=3&sn=b03e06d6bef1de2bcae561e8f607e0d4&chksm=80bb63fbb7cceaedf344010a30547122b2912d806763f268dbd4eea55a079936fe16ab55c8ed&scene=21#wechat_redirect) ## 原子性 cpu 在操作中不会切换任务的最小操作单元叫做原子,在并发系统中采用原子才可避免使用互斥锁 ## 加减法 ``` func AddInt32(addr *int32, delta int32 )(new int32) func AddInt64(addr *int64, delta int64)(new int64) func AddUint32(addr *uint32, delta uint32)(new uint32) func AddUint64(addr *uint64, delta uint64)(new uint64) func AddUintptr(addr *uintptr, delta uintptr)(new uintptr) ``` demo ``` var i int32 = 1 atomic.AddInt32(&i, 1) fmt.Println("i = i + 1 =", i) //减法通过 传负值 atomic.AddInt32(&i, -1) fmt.Println("i = i - 1 =", i) ``` ## 比较并交换 ``` func CompareAndSwaplnt32(addr *int32, old, new int32)(swapped bool) func CompareAndSwapInt64(addr *int64, old, new int64)(swapped bool) func CompareAndSwapPointer(addr *unsafe.Pointer, old, new unsafe.Pointer)(swapped bool) func CompareAndSwapUint32(addr *uint32, old, new uint32)(swapped bool) func CompareAndSwapUint64(addr *uint64, new uint64)( swapped bool) func CompareAndSwapUintptr(addr *uintptr, old, new uintptr)(swapped bool) ``` demo ``` // 交换之前先判断 old 和 new 对应的值是否相等,如果不相等才会交换 var a int32 = 1 var b int32 = 2 atomic.CompareAndSwapInt32(&a, a, b) fmt.Println("a, b:", a, b) ``` ## 加载 ``` func LoadInt32(addr *int32)(val int32) func LoadInt64(addr *int64) (val int64) func LoadPointer(addr *unsafe.Pointer)(val unsafe.Pointer) func LoadUint32(addr *uint32)(val uint32) func LoadUint64(addr *uint64)(val uint64) func LoadUintptr(addr *uintptr)(val uintptr) ``` demo ``` var x int32 = 100 y := atomic.LoadInt32(&x) fmt.Println("x, y:", x, y)//x, y: 100 100 ``` ## 存储 ``` var y int32 atomic.StoreInt32(&y,12) fmt.Println("y:", y) ``` ## 交换 与比较的差别是交换不需要考虑两值是否相等,会返回旧值 ``` var j int32 = 1 var k int32 = 2 old := atomic.SwapInt32(&j, k) fmt.Println("old,new:", old, j)//old,new: 1 2 ``` ## atomic.Value 存储原子的 interface{} 注意: 1. 存储值不能是 nil; 2. 再次存储时,值类型必须相等 如果违背这两条,编译时会抛出 panic ``` type b struct { name string } var B atomic.Value b1:=b{name:"ads"} B.Store(b1) B.Load() fmt.Printf("%+v\n", B.Load()) ```