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:
parent
ec54a84b0c
commit
ad896cc857
@ -16,10 +16,17 @@ func main() {
|
||||
// `range` builtin on the channel to iterate over
|
||||
// the values as they arrive every 500ms.
|
||||
ticker := time.NewTicker(500 * time.Millisecond)
|
||||
done := make(chan bool)
|
||||
|
||||
go func() {
|
||||
for t := range ticker.C {
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case t := <-ticker.C:
|
||||
fmt.Println("Tick at", t)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Tickers can be stopped like timers. Once a ticker
|
||||
@ -27,5 +34,6 @@ func main() {
|
||||
// channel. We'll stop ours after 1600ms.
|
||||
time.Sleep(1600 * time.Millisecond)
|
||||
ticker.Stop()
|
||||
done <- true
|
||||
fmt.Println("Ticker stopped")
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user