具有无缓冲 channel 的 Golang 例程

标签 go

我正在阅读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:

enter image description here

所以我想知道如果有三个或更多的 goroutine 共享同一个 channel 会怎么样?

比如三个goroutine GA GB GC 共享同一个channel c

现在一旦 GA 通过 c 发送消息,我们如何确保 GBGC 将收到消息?正如书中所说:

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/

相关文章:

go - 程序因 channel 而挂起

date - 解析 UTC 日期字符串并转换为不同的格式

go - 删除 slice 中的元素并返回删除的元素和剩余的元素

tomcat - 在go中解析tomcat日志文件的时间戳

go - 为什么/user/local/go 在 GoLand 中不被识别为 Go SDK

go - 使用 discordgo 发送私信

rest - 如何检查rest api中的截止日期是否大于明天

go - Golang中的“unresolve reference errors”

go - 有没有办法每隔一段时间做重复的任务?

javascript - 在 GAE 上的 Go 中显示由 html/template 产生的换行符