Does stopping a timer end the goroutine?

Issue

Does a simple goroutine like the below code that is stopped by stopping a timer become clean? Or stay in memory until the end of the program?

go func() {
    <-timer1.C //Will stop before firing.
    fmt.Println("Timer 1 fired")
}()

Solution

If the channel is closed, the Go routine will exit. If the channel remains open but nothing is ever sent over it, then the Go routine will "hang" forever, until the program exits.

If timer1 is a time.Timer, then Stop will not close the channel, as explained in the documentation: https://pkg.go.dev/time#Timer.Stop

Answered By – meagar

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.