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.

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

报告相同问题?

悬赏问题

  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗