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

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

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

问题

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

  1. func main(){
  2. for _, i := range x{
  3. go httpRequests(i, ch)
  4. }
  5. for i := range ch{
  6. print i
  7. }
  8. }
  9. func httpRequests(i, ch){
  10. for _, x := range y{
  11. go func(string x){
  12. // 对i进行一些操作
  13. ch <- result
  14. }(x)
  15. }
  16. }

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

英文:

I have a goroutine running in a for loop:

  1. func main(){
  2. for _, i := range x{
  3. go httpRequests(i, ch)
  4. }
  5. for i := range ch{
  6. print i
  7. }
  8. }
  9. func httpRequests(i, ch){
  10. for _, x := range y{
  11. go func(string x){
  12. do something with i
  13. ch &lt;- result
  14. }(x)
  15. }
  16. }

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

答案1

得分: 2

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

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

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

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:

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

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:

确定