go

Is this a goroutine Leak using Timer?


See example from gobyexample.com: https://gobyexample.com/timers

timer2 := time.NewTimer(time.Second)
go func() {
    <-timer2.C
    fmt.Println("Timer 2 fired")
}()
stop2 := timer2.Stop()
if stop2 {
    fmt.Println("Timer 2 stopped")
}

Question: after stopping the timer is go func() stuck forever? and if yes, what would be the correct way to handle this case?


Solution

  • If the timer is stopped before it fires, the goroutine will continue waiting. You have to stop it using another channel or a context:

    done:=make(chan struct{})
    go func() {
        select {
            case <-timer2.C:
                fmt.Println("Timer 2 fired")
            case <-done:
        }
    }()
    stop2 := timer2.Stop()
    close(done)