Select statements operate in several 'phases', before choosing a channel, or set of channels, that are ready all the arguments on the right hand side of the case expressions are evaluated. Here is your sample code rewritten to make it clear what is happening
func main() { sendCh := make(chan time.Duration, 1) x := randomSleep(1000, 2000) select { case <-time.After(1000 * time.Millisecond): log.Println("time after chan triggered") case sendCh <- x: log.Println("rand sleep triggered") } } On Thursday, 29 December 2016 06:46:03 UTC+11, Abhishek Singh wrote: > > Hi, > > Below is a sample example, where I'm trying to understand behaviour of > select statement. I was hoping the time.After() case clause to succeed but > observation is that either of those clauses are executed intermittently. > Would help if someone could share what's going on. > > func randomSleep(min, max int64) time.Duration { > rand.Seed(time.Now().UnixNano()) > sleepDuration := time.Duration(rand.Int63n(max-min)+min) * time.Millisecond > log.Printf("Sleep duration: %v\n", sleepDuration) > time.Sleep(sleepDuration) > return sleepDuration > } > > func main() { > sendCh := make(chan time.Duration, 1) > select { > case <-time.After(1000 * time.Millisecond): > log.Println("time after chan triggered") > case sendCh <- randomSleep(1000, 2000): > log.Println("rand sleep triggered") > } > } > > Go Playground - https://play.golang.org/p/6SosvxOUGL > > ---- > > I understand, I could workaround this behaviour via: > > func main() { > sendCh := make(chan time.Duration, 1) > go func () { sendCh <- randomSleep(1000, 2000) }() > select { > case <-time.After(1000 * time.Millisecond): > log.Println("time after chan triggered") > case <-sendCh: > log.Println("rand sleep triggered") > } > } > > Thanks. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.