猿问

Golang 为什么结果不等于 1000?

我有下一个代码


func main() {

    var counter int

    m := &sync.Mutex{}



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

        go func(m *sync.Mutex) {

            m.Lock()

            counter++

            m.Unlock()

        }(m)

    }


    fmt.Println(counter)

}

但是我不明白为什么计数器不等于1000?我正在使用互斥锁进行锁定,我正在等待程序等待解锁


MYYA
浏览 94回答 1
1回答

萧十郎

您正在所有 goroutines 完成之前打印结果。使用等待组等待它们:func main() {&nbsp; &nbsp; var counter int&nbsp; &nbsp; m := &sync.Mutex{}&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; wg.Add(1000)&nbsp; &nbsp; for i := 0; i < 1000; i++ {&nbsp; &nbsp; &nbsp; &nbsp; go func(m *sync.Mutex) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m.Lock()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m.Unlock()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; }(m)&nbsp; &nbsp; }&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; fmt.Println(counter)}
随时随地看视频慕课网APP

相关分类

Go
我要回答