Golang sync.Once使用

package main

import (
    "fmt"
    "sync"
)

func main() {
    var count int
    increment := func() {
        count++
    }

    var once sync.Once

    var increments sync.WaitGroup
    increments.Add(100)

    for i := 0; i < 100; i++ {
        go func() {
            defer increments.Done()
            once.Do(increment)
        }()
    }

    increments.Wait()

    fmt.Printf("Count is %d\n", count)
}

程序输出如下,


image.png

你可能感兴趣的:(Golang sync.Once使用)