How do I close all the goroutines that are "asleep"?

Issue

I have a goroutine running in a for loop:

    func main(){
           for _, i := range x{
               go httpRequests(i, ch)
           }

           for i := range ch{
              print i

        }
    }

func httpRequests(i, ch){
           for _, x := range y{
               go func(string x){
                  do something with i
                  ch <- result
              }(x)
           }


           }

When I run that, it says all goroutines are asleep. Any suggestions?

Solution

You started 3 goroutines (go serviceReq(i, httpCh)) passing them a channel. And then you receive on that channel only once (ch := (<-httpCh).serviceData).

Instead of that you should receive in a loop:

for resp := range httpCh {
    output = append(output, resp.serviceData)
}

Answered By – dev.bmax

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.