1
go 通道输出结果问题
source link: https://www.v2ex.com/t/809873
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
go 通道输出结果问题
package main
import (
"fmt"
)
func main() {
c := make(chan int, 5)
c <- 5
c <- 6
close(c)
fmt.Println(<-c)
}
这段代码输出的结果为什么是 5 ?没太看明白
12 条回复 • 2021-10-23 00:05:46 +08:00
Keystroke 5 小时 56 分钟前 via Android
我猜你是想问为什么 close 了还会接收到 5 而不是 0 。
因为接收操作的底层逻辑是先 qcount > 0,即缓冲队列是否还有元素。再判断 closed != 0,即管道是否关闭。所以,5 和 6 取出后才是 0 。
因为接收操作的底层逻辑是先 qcount > 0,即缓冲队列是否还有元素。再判断 closed != 0,即管道是否关闭。所以,5 和 6 取出后才是 0 。
labulaka521 5 小时 46 分钟前
For a channel c, the built-in function close(c) records that no more values will be sent on the channel. After calling close, and after any previously sent values have been received, receive operations will return the zero value for the channel's type without blocking.
@Keystroke
https://golang.org/ref/spec#Close
@Keystroke
https://golang.org/ref/spec#Close
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK