Go函数写入同一个地图
Go functions writing to the same map
我正在尝试熟悉 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 中,地图是通过引用传递的。为什么打印一张空地图?
正如评论中指出的,您需要同步访问地图,您对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)
}
sync.Map 是您实际要查找的内容,请在此处修改代码以适合您的用例,
https://play.golang.org/p/DPLHiMsH5R8
P.S。必须添加一些睡眠,以便程序不会在调用所有 go 例程之前完成。
我正在尝试熟悉 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 中,地图是通过引用传递的。为什么打印一张空地图?
正如评论中指出的,您需要同步访问地图,您对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)
}
sync.Map 是您实际要查找的内容,请在此处修改代码以适合您的用例,
https://play.golang.org/p/DPLHiMsH5R8
P.S。必须添加一些睡眠,以便程序不会在调用所有 go 例程之前完成。