1. 程式人生 > >golang goroutine 併發遞增

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