我正在尝试根据各种 goroutine 的输出填充 map 。为此,我创建了一个类型为 (map[key][]int) 的 channel
done := make(chan map[int][]int)
并将其连同键值一起传递给 workers goroutine,在示例中为 int。 因为我:= 0;我 < 10;我++ { 去 worker (我,完成) } 我想在读取 key 时填充我的 map 。目前我正在做如下
for i := 0; i < 10; i++ {
m := <-done
fmt.Println(m)
for k,v := range m {
retmap[k] = v
}
}
fmt.Println(retmap)
我觉得我做的不对。有没有更好的方法使用 channel 来做到这一点?任何建议将不胜感激?
Playground :https://play.golang.org/p/sv4Qk4hEljx
最佳答案
您可以为每个工作人员使用一个特定的 channel ,而不是在工作人员的结果对象中对该信息进行编码。像这样的东西:
func worker(done chan []int) {
fmt.Print("working...")
rnd := rand.Intn(10)
fmt.Println("Sleeping for ", rnd, "seconds")
for i := 0; i < rnd; i++ {
time.Sleep(time.Second)
}
fmt.Println("done")
// Send a value to notify that we're done.
done <- makeRange(0, rnd)
}
func main() {
channels := make([]chan []int, 10, 10)
for i := 0; i < 10; i++ {
channels[i] = make(chan []int)
go worker(channels[i])
}
retmap := make(map[int][]int)
for i := 0; i < 10; i++ {
retmap[i] = <-channels[i]
}
fmt.Println(retmap)
}
关于dictionary - 从 golang 中的 channel 响应填充 map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52984995/