Example of use of sync.WaitGroup golang

The following piece of code len(m)will not necessarily be printed as 10, and why? . If you want len(m)to print is 10, how should modify the code?

func main() {
    const N = 10
    m := make(map[int]int)
    wg := &sync.WaitGroup{}
    mu := &sync.Mutex{}
    wg.Add(N)
    for i := 0; i < N; i++ {
        go func() {
            defer wg.Done()
            mu.Lock()
            m[i] = i
            mu.Unlock()
        }()
    }
    wg.Wait()
    println(len(m))
}

len(m)When the 0-9 range are likely for or used in conjunction with co-routines, for passing to a number of uncertainties coroutine. Add to this anonymous function parameter passing, the result was 10.

func main() {
    const N = 10
    m := make(map[int]int)
    wg := &sync.WaitGroup{}
    mu := &sync.Mutex{}
    wg.Add(N)
    for i := 0; i < N; i++ {
        go func(i int) {
            defer wg.Done()
            mu.Lock()
            m[i] = i
            mu.Unlock()
        }(i)
    }
    wg.Wait()
    println(len(m))
}

Guess you like

Origin www.cnblogs.com/flythinking/p/12452742.html