首页 > 文章列表 > 关闭 golang 通道是否会导致 goroutine 强制同步?

关闭 golang 通道是否会导致 goroutine 强制同步?

281 2024-02-03
问题内容

如《Go 编程语言》一书(第 226 页)所述:

Communication over an unbuffered channel causes the sending and receiving goroutines to synchronize. Because of this, unbuffered channels are sometimes called synchronous channels. When a value is sent on an unbuffered channel, the receipt of the value happens before the reawakening of the sending goroutine.

关闭通道也会发生同样的情况吗?我的意思是,关闭通道的接收总是发生在刚刚关闭它的 goroutine 重新唤醒之前吗?

我记得读过一些与之相关的内容。我在书上搜索过,但没有找到。


正确答案


关闭通道不会像在无缓冲通道上发送那样强制 goroutine 同步。

Go 内存模型规范说:

调用 close() 的 goroutine 不会阻塞等待另一个 goroutine 接收零值。

向无缓冲通道发送值的 Goroutine 会阻塞,直到另一个 Goroutine 接收到该值。