相关疑难解决方法(0)

多个goroutines在一个频道上收听

我有多个goroutines尝试同时在同一个频道上接收.似乎在频道上开始接收的最后一个goroutine获得了价值.这是语言规范中的某个地方还是未定义的行为?

c := make(chan string)
for i := 0; i < 5; i++ {
    go func(i int) {
        <-c
        c <- fmt.Sprintf("goroutine %d", i)
    }(i)
}
c <- "hi"
fmt.Println(<-c)
Run Code Online (Sandbox Code Playgroud)

输出:

goroutine 4
Run Code Online (Sandbox Code Playgroud)

在操场上的示例

编辑:

我才意识到这比我想象的要复杂得多.消息在所有goroutine周围传递.

c := make(chan string)
for i := 0; i < 5; i++ {
    go func(i int) {
        msg := <-c
        c <- fmt.Sprintf("%s, hi from %d", msg, i)
    }(i)
}
c <- "original"
fmt.Println(<-c)
Run Code Online (Sandbox Code Playgroud)

输出:

original, hi from 0, hi from 1, hi from …
Run Code Online (Sandbox Code Playgroud)

go

65
推荐指数
4
解决办法
5万
查看次数

标签 统计

go ×1