去等goroutines,但同时做一些事情

去等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

我有以下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 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
并将其传入:请参阅