猿问

多个 goroutine 监听一个通道

我有多个 goroutine 试图同时在同一个频道上接收。似乎在通道上开始接收的最后一个 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)

输出:


goroutine 4


猛跑小猪
浏览 340回答 3
3回答

慕标琳琳

Effective Go解释了这个问题:接收器总是阻塞直到有数据要接收。这意味着您不能有超过 1 个 goroutine 监听 1 个通道并期望所有 goroutine 都收到相同的值。运行此代码示例。package mainimport "fmt"func main() {&nbsp; &nbsp; c := make(chan int)&nbsp; &nbsp; for i := 1; i <= 5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; go func(i int) {&nbsp; &nbsp; &nbsp; &nbsp; for v := range c {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("count %d from goroutine #%d\n", v, i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }(i)&nbsp; &nbsp; }&nbsp; &nbsp; for i := 1; i <= 25; i++ {&nbsp; &nbsp; &nbsp; &nbsp; c<-i&nbsp; &nbsp; }&nbsp; &nbsp; close(c)}即使有 5 个 goroutine 正在侦听通道,您也不会多次看到“count 1”。这是因为当第一个 goroutine 阻塞通道时,所有其他 goroutine 必须排队等待。当通道解除阻塞时,计数已经被接收并从通道中移除,因此下一个 goroutine 获得下一个计数值。
随时随地看视频慕课网APP

相关分类

Go
我要回答