Update tickers.go to not leak goroutine

The code in the example will leak a goroutine because ticker.Stop() does not close ticker.C.
There is no way to close ticker.C, so `for _ := range ticker` is not a generally safe example for using a ticker.
This commit is contained in:
tschundler 2018-10-17 13:52:04 -07:00 committed by GitHub
parent ec54a84b0c
commit ad896cc857
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -16,9 +16,16 @@ func main() {
// `range` builtin on the channel to iterate over // `range` builtin on the channel to iterate over
// the values as they arrive every 500ms. // the values as they arrive every 500ms.
ticker := time.NewTicker(500 * time.Millisecond) ticker := time.NewTicker(500 * time.Millisecond)
done := make(chan bool)
go func() { go func() {
for t := range ticker.C { for {
fmt.Println("Tick at", t) select {
case <-done:
return
case t := <-ticker.C:
fmt.Println("Tick at", t)
}
} }
}() }()
@ -27,5 +34,6 @@ func main() {
// channel. We'll stop ours after 1600ms. // channel. We'll stop ours after 1600ms.
time.Sleep(1600 * time.Millisecond) time.Sleep(1600 * time.Millisecond)
ticker.Stop() ticker.Stop()
done <- true
fmt.Println("Ticker stopped") fmt.Println("Ticker stopped")
} }