简体   繁体   English

从 golang 中的通道响应填充地图值

[英]Populate map values from channel response in golang

I am trying to populate a map based on output from various goroutines.我正在尝试根据各种 goroutine 的输出来填充地图。 For this I have created a channel of type (map[key][]int)为此,我创建了一个类型为 (map[key][]int) 的通道

done := make(chan map[int][]int)

and pass it to workers goroutine, along with the key value, which is int for the example.并将其与键值一起传递给 worker goroutine,在示例中为 int。 for i := 0;对于我:= 0; i < 10;我 < 10; i++ { go worker(i, done) } I want to populate my map as I read from the key. i++ { go worker(i, done) } 我想在从密钥中读取时填充我的地图。 Currently I am doing as below目前我正在做如下

for i := 0; i < 10; i++ {
    m := <-done
    fmt.Println(m)
    for k,v := range m {
        retmap[k] = v
    }
}
fmt.Println(retmap)

I feel I am not doing this correctly.我觉得我没有正确地做到这一点。 Is there a better way to do this using channels?有没有更好的方法来使用渠道来做到这一点? Any suggestions would be much appreciated?我们欢迎所有的建议?

playground: https://play.golang.org/p/sv4Qk4hEljx游乐场: https : //play.golang.org/p/sv4Qk4hEljx

You could use a specific channel per worker instead of encoding that information in the result object of the worker.您可以为每个工作人员使用特定的通道,而不是在工作人员的结果对象中对该信息进行编码。 Something like:就像是:

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)
}

Playground link游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM