【发布时间】:2016-12-12 03:00:30
【问题描述】:
我一定错过了什么,因为我还没有在网上找到这个非常基本的问题的答案。我正在使用能够保存三个int 值的缓冲通道。
然后我使用三个 goroutine 来填充它,并且我想在缓冲通道满后执行操作。
这是一个解释问题的sn-p:
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 的数组。我可以使用 3 次 <-difs 但我想知道 Go 是否提供了更清洁的东西来做到这一点。
【问题讨论】:
-
也许你应该使用select
-
这听起来像XY Problem——你通常不会等待一个通道被填满,因为你不能同时使用它的值。你想等待 goroutines 完成,这就是你使用 sync.WaitGroup 的目的。
标签: go