On Thursday 24 October 2024 at 18:42:35 UTC+2 robert engels wrote:
> In my experience, the OPΓÇÖs issue points to a code structure problem
> and not having a deterministic lifecycle for the channels.
I agree with this strongly. I think therere should be an owner of the
channel in some way, usually the sender. Because it is the sender, or it
knows there is know more sending, it is safe for it to close the
channel, as receiving on a closed channel doesn't panic.
That said, it is unfortunate that we have to do manual garbage
collecting now, since one nice thing about go is, its garbage collector.
We get all the problems you get in other languages where you need
ownership to know when to free and avoid use after free and so on.
Channels, are very much like this.
One way to handle this as robert mentiones, may be to have something
higher up deal with the channels, provide them to the code in question.
In terms of sender should be owner/closer, it is not always as simple as
it sounds. Sometimes you need special techniques, and a whole lot of
control flow to get this right.
For example here in the io.Pipe code:
https://cs.opensource.google/go/go/+/refs/tags/go1.23.2:src/io/pipe.go;l=195It is using an extra "done" channel to cancel sends/receives on the main
channel and does extra guard selects on it, due to select pseudo
randomness. Additionally, it has a sync.Once to prevent panic when
closing the channel twice.