我正在阅读Go in action
这本书。
无缓冲 channel
是这样描述的:
An unbuffered channel is a channel with no capacity to hold any value before it’s received. These types of channels require both a sending and receiving goroutine to be ready at the same instant before any send or receive operation can complete. If the two goroutines aren’t ready at the same instant, the channel makes the goroutine that performs its respective send or receive operation first wait. Synchronization is inherent in the interaction between the send and receive on the channel. One can’t happenwithout the other.
本书使用下图来说明unbuffered channel
:
所以我想知道如果有三个或更多的 goroutine
共享同一个 channel
会怎么样?
比如三个goroutine GA
GB
GC
共享同一个channel c
现在一旦 GA
通过 c
发送消息,我们如何确保 GB
和 GC
将收到消息?正如书中所说:
These types of channels require both a sending and receiving goroutine to be ready at the same instant
这意味着当两个 goroutine 正在交换消息时,第三个 goroutine 必须丢失消息。
这是 goroutine 运行的正确方式吗?
最佳答案
通过 channel 发送的消息被传送到恰好一个接收goroutine。
假设您有三个 goroutine,一个发送,两个接收,发送 goroutine 需要发送两个消息来让两个接收 goroutine 解锁,比如 this :
var c = make(chan int)
go func() { fmt.Printf("got %d\n", <-c) }()
go func() { fmt.Printf("got %d\n", <-c) }()
c <- 1
c <- 2
另请注意,这还需要接收 goroutines 每个读取 exactly one 消息。如果他们循环执行此操作,其中一个可能会收到两条消息,而另一个则不会。
关于具有无缓冲 channel 的 Golang 例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48416807/