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)
}
原文链接:https://www.f2er.com/go/187159.html