时间:2025-07-23 23:39
人气:
作者:admin
func AtomicCounterDemo() {
var count int32
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 1000; j++ {
atomic.AddInt32(&count, 1)
}
}()
}
wg.Wait()
fmt.Println("最终计数器的值:", count)
}
func AddInt32(addr *int32, delta int32) int32
1. count 是一个 int32 类型的变量。
2. &count 表示取 count 变量的内存地址,也就是 count 的指针。
3. 原子操作需要直接操作变量的内存地址,才能保证并发安全。
var count int32
atomic.AddInt32(&count, 1) // 传入 count 的地址
&,直接写 atomic.AddInt32(count, 1),会报错,因为类型不匹配(需要指针,实际传了值)。