How is ticker exit from for-range?


(cinematik) #1

https://play.golang.org/p/7FI8e7EVJBd

When for-range loop exits is it exit by return from gorotine?
In the above example it never prints line 15, why?


(Norbert Melzer) #2

The loop will never exit, as the tickers channel never gets closed.

Because the for loop is infinite due to the fact that the tickers channel will never be closed.


(cinematik) #3

hm, that behavior is quite confusing. it looks like a memory leaking.


(Norbert Melzer) #4

The problem with closing is, if you had the following code, you’d get a problem if the tickers channel gets closed, as a closed channel always returns the zero-value:

for {
  select {
    case t <- ticker.C:
      // ...
  }
}

Though if you layed out your code in a different manor, ensuring that stopped tickers don’t get referenced anymore, then even the still left open channel will be GC’d eventually.


(cinematik) #5

I’ve fount that in my case this will solve.