简体   繁体   English

无缓冲通道上的循环范围

[英]Range for loop over an unBuffered Channel

I'm new to golang and going over the gotour .我是 golang 的新手,正在学习 gotour I have following code which works perfectly as it should.我有以下代码可以完美运行。

package main

import (
    "fmt"
)

func fibonacci(n int, c chan int) {
    x, y := 0, 1
    for i := 0; i < n; i++ {
        c <- x
        x, y = y, x+y
    }
    close(c)
}

func main() {
    c := make(chan int, 5)
//  c := make(chan int)     //doesn't work, why ?
    go fibonacci(cap(c), c)
    for i := range c {
        fmt.Println(i)
    }
}

But when I use an unbuffered channel instead of a buffered one, I don't get any output, why's that so?但是当我使用无缓冲通道而不是缓冲通道时,我没有得到任何 output,为什么会这样?

When you pass cap(c) through to the fibonacci function, what value is passed through?当您将 cap(c) 传递给斐波那契 function 时,传递了什么值? on the buffered channel the n == 5 , on the unbuffered channel n == 0在缓冲通道上n == 5 ,在非缓冲通道上n == 0

and your for loop和你的 for 循环

for i := 0; i < 0; i++ {

Actually, this is a really bad way of handling the situation.实际上,这是处理这种情况的一种非常糟糕的方式。 You are requiring the number of channels to be equal to the number of iterations.您要求通道数等于迭代次数。

Using a channel in this way I would not recommend, think of the channel as being able to operate concurrently, which is not something you would want to do in this scenario!我不建议以这种方式使用通道,将通道视为能够并发操作,这不是您在这种情况下想要做的事情!

If you pass the number in separately to the number of routines, then the unbuffered channel will work as expected:如果您将数字单独传递给例程的数量,那么无缓冲通道将按预期工作:

https://play.golang.org/p/G1b2vjTUCsV https://play.golang.org/p/G1b2vjTUCsV

cap(c) will be zero if channel is un-buffered.如果通道未缓冲,则cap(c)将为零。 See the modified program查看修改后的程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM