【发布时间】:2020-08-20 03:50:48
【问题描述】:
下面的代码每次执行后都会打印不同的值,但我希望值相同,如何在不使用time.Sleep的情况下更改下面的代码
package main
import (
"fmt"
"sync"
)
var total int
var wg sync.WaitGroup
// Inc increments the counter for the given key.
func inc(num int) {
total += num
wg.Done()
}
// Value returns the current value of the counter for the given key.
func getValue() int {
return total
}
func main() {
for i := 1; i <= 1000; i++ {
wg.Add(1)
go inc(i)
}
wg.Wait()
fmt.Println(getValue())
}
【问题讨论】: