在一个select-case语句中从一个通道读取并写入另一个通道。

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

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 &lt;- time.Now() // We don&#39;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 &lt;- &lt;-ticker.C:
	case &lt;-triggerChan:
		worker.DoWork()
	}
}

A value is written to triggerChan before the first select to direct it into case &lt;-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 &lt;- &lt;-ticker.C would block, or would it happily soft-lock unaware of what is trying to be done with the result of &lt;-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...

huangapple
  • 本文由 发表于 2021年7月1日 23:05:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/68212654.html
匿名

发表评论

匿名网友

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

确定