英文:
Read from one channel and write to another within one select-case
问题
考虑以下这段Go代码,它会立即调用worker.DoWork()
,然后每分钟调用一次:
triggerChan := make(chan time.Time, 1)
triggerChan <- time.Now() // 我们不想等一分钟才调用worker.DoWork()的第一次调用。
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case triggerChan <- <-ticker.C:
case <-triggerChan:
worker.DoWork()
}
}
在第一个select
之前,一个值被写入triggerChan
,以便将其定向到case <-triggerChan
,从而立即调用worker.DoWork()
。然而,如果ticker.C
已经有一个可用的值(如果我们使用time.Microsecond
而不是time.Minute
,这种情况并不太可能),会发生什么?运行时会注意到triggerChan <- <-ticker.C
会阻塞吗?还是它会快乐地软锁定,不知道对<-ticker.C
的结果要做什么处理?它是否意识到这种"从通道到通道"的情况?
英文:
Consider this Go code which shall call worker.DoWork()
immediately and then once every minute:
triggerChan := make(chan time.Time, 1)
triggerChan <- time.Now() // We don't want to wait a minute for the first call of worker.DoWork() to happen.
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case triggerChan <- <-ticker.C:
case <-triggerChan:
worker.DoWork()
}
}
A value is written to triggerChan
before the first select
to direct it into case <-triggerChan
to have worker.DoWork()
called immediately. However, in the case that ticker.C
already had a value available (not all that unlikely if we used something like time.Microsecond
instead of time.Minute
), what would happen? Would the runtime see that triggerChan <- <-ticker.C
would block, or would it happily soft-lock unaware of what is trying to be done with the result of <-ticker.C
? Is it aware of this "from channel into channel"-situation?
答案1
得分: 3
select
根据 triggerChan
的状态进行决策,但是它首先评估发送操作的右侧表达式。因此,在进入时,它会等待 <-ticker.C
返回。然后它会从通道中读取第一个值,然后写入它...
英文:
The select
decides based on the state of triggerChan
, however it first evaluates the right hand side expressions for send operations.
So on entry, it will wait until <-ticker.C returns. Then it will read the first value from the channel, and then write to it...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论