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?
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...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.