dongzhuifeng1843 2017-08-28 08:38
浏览 41

通道消耗多次执行例程,导致数据丢失

I am a newbie to Go. In my example below, multiple go routines are consuming from an unbuffered channel.

Code :

var c = make(chan int)

func f() {
    for val := range c {    
        fmt.Printf("routine 1 : %v
", val)
    }
}   

func g() {
    fmt.Printf("routine 2 : %v
", <-c)
}

func main() {
    go f()
    go g()
    c <- 0
    c <- 1
    c <- 2
    c <- 3
    c <- 4
    c <- 5
    close(c) 
}

The output was :

routine 1 : 0
routine 1 : 2
routine 2 : 1
routine 1 : 3
routine 1 : 4

Value 5 is missing from this and never gets printed ! Why is this happening? If I remove the call - go g(), it works perfectly.

Also, if I make the channel buffered, say :

var c = make(chan int, 10)

There is no output at all. I understand that for unbuffered channel, the send completes after receive completes, which is not the case for buffered. Still, for buffered case, if channel has not yet sent any int, wouldn't the for loop be blocked considering it a nil channel?

Please help out with both my queries. Appreciate all the inputs.

  • 写回答

3条回答 默认 最新

  • douyao2529 2017-08-28 08:51
    关注

    As soon as 5 is consumed, the program exits. There's no time for it to print the output. If you run the program enough times, you may find that on some occasions, it does happen to print the output before it closes, but it'll be purely random.

    You need to add some mechanism to wait for your channels to finish, before exiting the program.

    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像