简体   繁体   中英

Populate map values from channel response in golang

I am trying to populate a map based on output from various goroutines. For this I have created a channel of type (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. for i := 0; i < 10; i++ { go worker(i, done) } I want to populate my map as I read from the key. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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