英文:
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 <- 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 := (<-httpCh).serviceData
).
Instead of that you should receive in a loop:
for resp := range httpCh {
output = append(output, resp.serviceData)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论