Reputation: 3300
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?
Upvotes: 0
Views: 92
Reputation: 51632
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...
Upvotes: 3