去等goroutines,但同时做一些事情
我有以下go代码:去等goroutines,但同时做一些事情,go,concurrency,goroutine,Go,Concurrency,Goroutine,我有以下go代码: func execTask(input int, results chan<- int) { //do stuff (in my case, start process and return something) results <- someResult } func main() { results := make(chan int) for _, task := range tasks { go execT
func execTask(input int, results chan<- int) {
//do stuff (in my case, start process and return something)
results <- someResult
}
func main() {
results := make(chan int)
for _, task := range tasks {
go execTask(task, results)
}
for result := range results {
fmt.Println(result)
}
}
func execTask(input int,results chan由于未关闭results
通道,您将收到死锁错误。因此,main
会继续等待有关results
的更多数据,即使在所有execTask
完成之后,也没有其他写入results
您可以使用sync.WaitGroup
修复此问题:
func main() {
var wg sync.WaitGroup
results := make(chan int)
wg.Add(len(tasks))
for _, task := range tasks {
go func(task int) {
defer wg.Done()
execTask(task, results)
}(task)
}
go func() {
wg.Wait() // wait for each execTask to return
close(results) // then close the results channel
}
for result := range results {
fmt.Println(result)
}
}
至于在其他进程仍在执行时处理execTask
结果,您已经有了正确的想法。只需在results
range循环中处理它们。如果您想要更多的并发执行,请在其中启动更多的goroutin。results:=make(chan int)for u,task:=range tasks{go execTask(task,results)}task也在调用results,这可能会导致死锁。不要像那样在闭包中的范围内使用task
。让闭包接受task int
并将其传入:请参阅