[SOLVED] Populating an array using Channels in a WaitGroup routine


This Content is from Stack Overflow. Question asked by Ufder

I want to populate an array of arrays inside a subroutine. I am trying to do this using a channel. I am learning go, so unclear if this is the right way, so please correct me if I am going in the wrong direction, but my code never returns. What am I doing wrong?

values := [3][4]string{{"A", "B", "C", "D"}}

var wg sync.WaitGroup
wg.Add(4) // one thread per index, total 4 indexes

for idx, url := range envmap {
    go func(name string, url []string) {
        defer wg.Done()
        values[1][idx] = "foo"
        values[2][idx] = "bar"
        c <- values
    }(name, url)



From code it looks like channel c is not read, and code is stuck there.

This code doesn’t need any synchronisation (channel etc.) because each goroutine is working on different part of values, gr1->[xx,0], gr2->[xx,1], gr3-> [xx,2], gr4-> [xx,3].

Just remove the channel c from the code and this should work fine.

Change goroutine code to:

go func(idx int, url string, arr *[3][4]string) {
  defer wg.Done()
  arr[1][idx] = "someone"
  arr[2][idx] = "something"
}(idx, url, &values)

This Question was asked in StackOverflow by Ufder and Answered by s3vt It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?