如何关闭所有处于“休眠”状态的 goroutine?

huangapple go评论97阅读模式
英文:

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

问题

我有一个在for循环中运行的goroutine:

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){
            // 对i进行一些操作
            ch <- result
        }(x)
    }
}

当我运行这段代码时,它显示所有的goroutine都处于休眠状态。有什么建议吗?

英文:

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 &lt;- result
              }(x)
           }
 

           }

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

答案1

得分: 2

你启动了3个goroutine(go serviceReq(i, httpCh)),并将它们传递给一个通道。然后你只接收了一次该通道的数据(ch := (<-httpCh).serviceData)。

相反,你应该使用循环接收数据:

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

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

Instead of that you should receive in a loop:

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

huangapple
  • 本文由 发表于 2017年5月7日 03:37:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/43824649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定