我正在嘗試熟悉 go 例程。我編寫了以下簡單程序來將 1-10 的數字平方存儲在地圖中。func main() { squares := make(map[int]int) var wg sync.WaitGroup for i := 1; i <= 10; i++ { go func(n int, s map[int]int) { s[n] = n * n }(i, squares) } wg.Wait() fmt.Println("Squares::: ", squares)}最后,它打印一張空地圖。但是在 go 中,地圖是通過引用傳遞的。為什么打印一張空地圖?
2 回答

HUWWW
TA貢獻1874條經驗 獲得超12個贊
正如評論中指出的那樣,您需要同步對地圖的訪問并且您的使用sync.WaitGroup不正確。
試試這個:
func main() {
squares := make(map[int]int)
var lock sync.Mutex
var wg sync.WaitGroup
for i := 1; i <= 10; i++ {
wg.Add(1) // Increment the wait group count
go func(n int, s map[int]int) {
lock.Lock() // Lock the map
s[n] = n * n
lock.Unlock()
wg.Done() // Decrement the wait group count
}(i, squares)
}
wg.Wait()
fmt.Println("Squares::: ", squares)
}
- 2 回答
- 0 關注
- 137 瀏覽
添加回答
舉報
0/150
提交
取消