我一定是漏掉了什么,因为我还没有在网上找到这个非常基本的问题的答案。我正在使用能够容纳三个 int
的缓冲 channel 值。
然后我使用三个 goroutine 来填充它,一旦缓冲 channel 已满,我想执行一个操作。
这是解释问题的片段:
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 是否提供了更简洁的方法来做到这一点。
最佳答案
等待使用 channel 本身,就像这个工作示例代码:
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} // Initialization of the slice a and 0 < n < len(a) - 1.
difs := make(chan int, 3)
go routine(a[0:4], difs)
go routine(a[4:8], difs)
go routine(a[8:12], difs)
result := []int{<-difs, <-difs, <-difs}
fmt.Println(result) // Display the first result returned by one of the routine.
}
func routine(a []int, out chan<- int) {
result := 0 // Long computation.
for _, v := range a {
result += v
}
out <- result
}
输出:
[10 42 26]
关于go - 等待缓冲 channel 满,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38793573/