gpt4 book ai didi

go - Go 中使用 channel 的斐波那契数列

转载 作者:IT王子 更新时间:2023-10-29 02:05:17 26 4
gpt4 key购买 nike

我正在关注 tour.golang.org 上的示例。

我基本上理解这个例子,我唯一的问题是为什么当我们传递 0 退出 channel 时它会停止?不管是否传递 0 来退出,x 总是有一个值。所以 select 不应该总是落在 case 'c <- x' 上吗?

func fibonacci(c chan int, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
return
}
}
close(c)
}

func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}

最佳答案

there is always a value for x. So shouldn't select always fall on case 'c <- x' ?

不,因为这个 channel 是无缓冲的,发送将阻塞直到有人可以从它接收。

Effective Go 上阅读有关 channel 的信息:

Receivers always block until there is data to receive. If the channel is unbuffered, the sender blocks until the receiver has received the value. If the channel has a buffer, the sender blocks only until the value has been copied to the buffer; if the buffer is full, this means waiting until some receiver has retrieved a value.

此外,如果 select 语句中的 2 个 case 可以继续,one is picked pseudo-randomly .

If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.

关于go - Go 中使用 channel 的斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30665829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com