golang goroutine 并发递增

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)
}

猜你喜欢

转载自blog.csdn.net/qq_17612199/article/details/80364916