Go 中使用通道的斐波那契数列

Fibonacci in Go using channels

我正在按照 tour.golang.org 上的示例进行操作。

我基本上理解这个例子,我唯一的问题是为什么当我们传递 0 退出频道时它会停止?不管是否传递 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' ?

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

了解 Effective Go 上的频道:

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 个案例可以继续,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.