sync.WaitGroup 没有按照我的预期运行,我在这里错过了什么?

鉴于以下情况:


package main


import (

    "fmt"

    "sync"

)


func main() {

    n := 100


    var wg sync.WaitGroup

    wg.Add(n)


    x := 0

    for i := 0; i < n; i++ {

        go func() {

            defer wg.Done()

            x++

        }()

    }


    wg.Wait()

    fmt.Println(n, x)

}

我希望在最后打印时x总是到达100,但有时打印低至95. 我在这里缺少什么?



慕姐8265434
浏览 133回答 2
2回答

catspeake

有一场比赛x。一种解决方法是x使用互斥锁进行保护:var mu sync.Mutexvar wg sync.WaitGroupwg.Add(n)x := 0for i := 0; i < n; i++ {&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; mu.Lock()&nbsp; &nbsp; &nbsp; &nbsp; x++&nbsp; &nbsp; &nbsp; &nbsp; mu.Unlock()&nbsp; &nbsp; }()}wg.Wait()fmt.Println(n, x)我建议在 Go 程序中有多个 goroutine 时发现一些令人费解的事情时运行竞态检测器。

FFIVE

使用 sync.atomic 方法以原子方式访问 x。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "sync/atomic")func main() {&nbsp; &nbsp; n := 100&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; wg.Add(n)&nbsp; &nbsp; var x int32&nbsp; &nbsp; for i := 0; i < n; i++ {&nbsp; &nbsp; &nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; atomic.AddInt32(&x, 1)&nbsp; &nbsp; &nbsp; &nbsp; }()&nbsp; &nbsp; }&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; fmt.Println(n, x)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go