4 ms·
It's very important when looking at the channel method to realise that goroutines are NOT garbage collected. If there is any chance of the loop calling break o
by Laremere 13y ago
It's very important when looking at the channel method to realise that goroutines are NOT garbage collected. If there is any chance of the loop calling break or panicking, there is a chance of leaking goroutines. Since you might not know how your code is going to be used, this is an issue.
A possible solution is to use two channels, the items channel and a fail channel. Whenever your iterator sends, it needs to use a select which either sends the item on the channel, or receives from a fail channel (in which case it exits the function.)
I think while the channel method looks nice because of Go's special treatment of it's basic types (for better or worse,) it's not practically the best answer you should be using in your code.
- ewencp 13y agoI mentioned this pitfall, but didn't show how to solve it. I haven't seen a complete example yet and didn't take the time to work out the details yet. I'm less concerned about complexity in the iterator implementation, but handling this correctly also seemed to require changing the caller code since it needs to send something on the fail channel. Then the onus is on the caller to remember to do so, which is just as bad as having to remember not to call break. Of course, whether this is a real issue or not also depends on whether you're writing internal or external APIs. There are lots of other ways to generate uncollectible garbage too...
- cmccabe 13y agoUse "defer close(ch)". If there is a break or a panic, the channel will be closed.
- Laremere 13y agoIf there is a break or panic in the iterator, not the loop using the iterator. If the loop using the iterator closes the channel, the program will crash.
- cmccabe 13y agoThe sender is supposed to close the channel to signify to the receiver that there is no more data to be sent. The receiver is not supposed to close the channel. (You could hack around this by recovering from the panic, but this is bad style.) https://groups.google.com/forum/#!topic/golang-nuts/RmfHSHE9e30 https://groups.google.com/forum/#!topic/golang-nuts/RmfHSHE9... Note that there is no requirement that you close channels-- they aren't like file descriptors. They will be garbage collected after they're no longer needed. goroutines, on the other hand, will stick around unless you clean them up. goroutines aren't iterators, and you shouldn't use them as iterators. They're more analogous to threads.