不同渠道传入的数据在选择语句中是否会被忽略?

huangapple go评论80阅读模式
英文:

Can data coming from different channels into select statement get ignored?

问题

在Go语言中,如果通过通道传入的数据在select语句中没有被及时捕获,是否可能被忽略?

例如,假设有以下select语句:

for {
    select {
    case <-timer.C:
        // block A
    default:
        // block B需要2秒钟的时间
    }
}

如果在block B正在运行时计时器结束,block A是否会在下一次循环迭代中运行,还是通道中的数据会丢失?

英文:

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 &lt;-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

得分: 3

当计时器到期时,它将在通道C上发送当前时间。如果此时没有任何人从C中读取数据,发送操作将会阻塞,因此它会等待直到值被接收。在这种情况下,它会等待到循环的下一次迭代。

通道被设计为一种同步机制,因此不要求读取者和写入者已经同步。

英文:

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.

huangapple
  • 本文由 发表于 2015年5月8日 02:04:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/30108562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定