dongxin2734 2019-09-17 13:43
浏览 138
已采纳

添加元素后通道长度为零

I learn buffered channels in Go and some magic is hidden from me. I have this code

package main

import (
    "fmt"
)

func write(ch chan int) {
    for i := 1; i <= 5; i++ {
        ch <- i
        fmt.Printf("Channel's length is %d
", len(ch))
    }
    close(ch)
}
func main() {
    ch := make(chan int, 2)
    go write(ch)

    for v := range ch {
        fmt.Println(v)
    }
}

The output is

Channel's length is 0
Channel's length is 1
Channel's length is 2
1
2
3
4
Channel's length is 2
Channel's length is 0
5

Why is the channel's length on the first iteration in write goroutine is zero? What do I don't know?

  • 写回答

1条回答 默认 最新

  • drgweamoi473182981 2019-09-18 08:29
    关注

    As per the concept of GO buffer, you can push elements in channels as per defined buffer size (in your case it is 2). But at the time an element is pushed into channel, same is being read by the main GO routine which leads to a decrease in the size of channel to zero. So, if you put some time.Sleep before your read statement you will get the expected result.

    `

    package main
    import (
        "fmt"
        "time"
    )
    
    func write(ch chan int) {
        for i := 1; i <= 5; i++ {
            ch <- i
            fmt.Printf("Channel's length is %d
    ", len(ch))
        }
        close(ch)
    }
    func main() {
        ch := make(chan int, 2)
        go write(ch)
        time.Sleep(2*time.Second)
        for v := range ch {
            fmt.Println(v)
            time.Sleep(2*time.Second)
        }
    }`
    

    Output for the above code is:

    Channel's length is 1

    Channel's length is 2

    1

    Channel's length is 2

    2

    Channel's length is 2

    3

    Channel's length is 2

    4

    5

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料