关闭 golang 通道是否也会强制 goroutine 同步?
php小编西瓜在这里为大家解答一个关于golang通道的问题:关闭golang通道是否也会强制goroutine同步?通常情况下,关闭通道不会强制goroutine同步,但关闭通道会触发对通道的读操作返回零值和一个布尔值。如果通道中还有未读取的数据,那么读取操作会返回数据和true;如果通道中没有未读取的数据,那么读取操作会返回零值和false。因此,在关闭通道后,可以通过读取通道来判断是否已经读取完通道中的所有数据。
问题内容
如《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. 登录后复制