go - 等待缓冲 channel 满

标签 go

我一定是漏掉了什么,因为我还没有在网上找到这个非常基本的问题的答案。我正在使用能够容纳三个 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/

相关文章:

go - golang 中的 math.Pow 是否适合这个公式?

mysql - 使用golang在mysql中创建数据库

go - Hyperledger Custom Chaincode部署错误

go - 如何使用 Go 获得最近的城市地理坐标?

Go << 和 >> 运算符

arrays - 为什么不能在 Go 中将变量作为多维数组大小?

c - XMPP 服务器的 libxml2 与 expat

go - 如果前一个处理程序 gin 出错,如何停止执行下一个处理程序

go - sort.Sort 不修改数组

json - 如何将 jsonb 编码为 golang 中 http 响应的一部分