我一定错过了一些东西,因为我还没有找到在线解答这个非常基本的问题。我正在使用能够保存三个int
值的缓冲通道。等待一个缓冲通道充满
然后,我使用三个goroutines来填充它,并且我想在缓冲通道已满时执行操作。
这里是一个片段说明问题:
func main() {
// Initialization of the slice a and 0 < n < len(a) - 1.
difs := make(chan int, 3)
go routine(a[:n], difs)
go routine(a[n + 1:], difs)
go routine(a[n - 1:n + 1], difs)
fmt.Println(<-difs) // Display the first result returned by one of the routine.
}
func routine(a []int, out chan<- int) {
// Long computation.
out <- result
}
我想更新我的代码,以便fmt.Println(<-difs)
显示器int
数组当所有的值已经计算出来。我可以使用三次<-difs
,但我想知道Go是否提供了更干净的方法。
也许你应该使用[select](https://tour.golang.org/concurrency/5) –
这听起来就像[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - 你通常不会等待频道充满,因为你可以'然后同时从中消费价值。您希望等待goroutine完成,这是您使用sync.WaitGroup的原因。 – JimB