dongpu3347 2016-06-07 22:59
浏览 18

在频道中选择

The following is one example code for select. I don't understand why the second select doesn't execute the first case? The output seems to be:

messages := make(chan string)
signals := make(chan bool)

// Here's a non-blocking receive. If a value is
// available on `messages` then `select` will take
// the `<-messages` `case` with that value. If not
// it will immediately take the `default` case.
select {
case msg := <-messages:
    fmt.Println("received message", msg)
default:
    fmt.Println("no message received")
}

// A non-blocking send works similarly.
msg := "hi"
select {
case messages <- msg:
    fmt.Println("sent message", msg)
default:
    fmt.Println("no message sent")
}

// We can use multiple `case`s above the `default`
// clause to implement a multi-way non-blocking
// select. Here we attempt non-blocking receives
// on both `messages` and `signals`.
select {
case msg := <-messages:
    fmt.Println("received message", msg)
case sig := <-signals:
    fmt.Println("received signal", sig)
default:
    fmt.Println("no activity")
}

After I run the code, the output:

no message received
no message sent
no activity

Updated: I know why the second select goes to default now. What about the third one?

  • 写回答

1条回答 默认 最新

  • doulun1915 2016-06-07 23:01
    关注

    messages is unbuffered, and no other Go routine is blocked waiting for something to be received. Since the send operation will block, the default case is executed.

    Compare this to the behaviour of a buffered channel or when another Go routine is blocked reading on the channel.

    From the language specification:

    1. If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen.
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?