dpdkqls6399 2019-01-19 10:05
浏览 86
已采纳

进入频道:虽然不向频道推送任何内容,但仍消耗频道中的数据

For example I have this code:

package main

import (
    "fmt"
)

func main() {

    c1 := make(chan interface{})
    close(c1)
    c2 := make(chan interface{})
    close(c2)

    var c1Count, c2Count int
    for i := 1000; i >= 0; i-- {
        select {
        case <-c1:
            c1Count++
        case <-c2:
            c2Count++
        }

    }
    fmt.Printf("c1Count: %d
c2Count: %d
  ", c1Count, c2Count)
}

When running, the output will be:

c1Count: 513
c2Count: 488

The thing I don't know is: we create c1 and c2 channel without doing anything. Why in select/case block, c1Count and c2Count can increase value ?

Thanks

  • 写回答

1条回答 默认 最新

  • dongye1934 2019-01-19 10:15
    关注

    The Go Programming Language Specification

    Close

    After calling close, and after any previously sent values have been received, receive operations will return the zero value for the channel's type without blocking. The multi-valued receive operation returns a received value along with an indication of whether the channel is closed.


    You are counting zero values.

    For example,

    package main
    
    import (
        "fmt"
    )
    
    func main() {
    
        c1 := make(chan interface{})
        close(c1)
        c2 := make(chan interface{})
        close(c2)
    
        var c1Count, c2Count int
        var z1Count, z2Count int
        for i := 1000; i >= 0; i-- {
            select {
            case z1 := <-c1:
                c1Count++
                if z1 == nil {
                    z1Count++
                }
    
            case z2 := <-c2:
                c2Count++
                if z2 == nil {
                    z2Count++
                }
            }
    
        }
        fmt.Printf("c1Count: %d
    c2Count: %d
    ", c1Count, c2Count)
        fmt.Printf("z1Count: %d
    z2Count: %d
    ", z1Count, z2Count)
    }
    

    Playground: https://play.golang.org/p/tPRkqXrAFno

    Output:

    c1Count: 511
    c2Count: 490
    z1Count: 511
    z2Count: 490
    

    The Go Programming Language Specification

    For statements

    For statements with range clause

    For channels, the iteration values produced are the successive values sent on the channel until the channel is closed. If the channel is nil, the range expression blocks forever.

    Close is useful with a for statement with a range clause.

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

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记