package main
import (
"sync/atomic"
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
var a int32 = 0 // goroutine指向的外部变量地址
for i := 1; i < 100; i++ {
wg.Add(1)
go func(incr int32) {
for !atomic.CompareAndSwapInt32(&a, a, a+incr) { // 悲观锁
}
wg.Done()
}(int32(i))
}
wg.Wait()
fmt.Println(a)
}
golang goroutine 并发递增
最新推荐文章于 2024-06-11 21:08:06 发布