dsm13698679318
dsm13698679318
2015-05-07 18:04

来自不同渠道的数据进入选择语句是否可以忽略?

  • channel
已采纳

Is it possible for data coming in through a channel in golang to get ignored if it is not caught at the right moment inside a select statement?

For example, lets say there is this select statement:

for {
    select {
    case <-timer.C:
        //block A
    default:
        // block B takes 2 seconds.
    }
}

If timer ends while block B is running, does block A still run in the next iteration of the loop or does the channel's incoming data get lost?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doudundian9558 doudundian9558 6年前

    When the timer expires, it will send the current time on C. If no one is reading from C at the time, the send will block, so it will wait until the value is received. In this case, it will wait till the next iteration of the loop.

    Channels are designed to be a synchronization mechanism, so they don't require readers and writers to be already synchronized.

    点赞 评论 复制链接分享