How is ticker exit from for-range?

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?

2 Likes

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.

3 Likes

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

2 Likes

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.

2 Likes

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

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.