Search code examples
goconcurrency

Multiple tickers in Go's select statement's cases


When I run the following Go 1.18 code, I expect to see both messages being printed repeatedly to standard output, one after another. However, I only see "ping" being printed repeatedly. Why? The select statement must be executing both cases, since there are two different channel operations, and the channels themselves are different.

for {
    select {
    case <-time.NewTicker(time.Millisecond * 400).C:
        fmt.Println("ping")
    case <-time.NewTicker(time.Millisecond * 600).C:
        fmt.Println("pong")
    }
}

Solution

  • You are creating a new ticker in the case. The select statement evaluates the cases first, which means, it creates two timers, and after the shorter one ticks, it creates another pair of timers. Next time around, the shorter one will be picked again.

    Create the two tickers outside the for loop.