Only the sole/final sender (or some delegate thereof) should ever close a channel. Closing a channel is really only necessary as a method of signaling the consumer that there is no more data to come, it doesn't do anything like deallocate the channel or even any buffered messages stored in it. A consumer shouldn't be using the close mechanism to notify the senders to stop sending; it should have an out-of-band method of doing so, which will then allow it to process any final data that is still queued up for it before they're all done. It's not usually that difficult to have a waitgroup triggered off of the completion of all of the senders that will close the channel, and it's also not usually difficult to have a select in the senders which allows them to receive a "stop sending data" signal.
Information on a channel only flows from sender to receiver.
Close is a signal to the *receivers* that the *senders* are done.
Adding some kind of support for detecting send on a closed
channel would be sending information back to a sender.
There is no requirement that channels be closed.
It's fine to just stop using a channel, unlike, say, file descriptors.
> I've read on other discussions that the idiomatic way to manage this
> is to have the sender close the channel. How does this work if there
> are multiple senders?
They have to coordinate amongst themselves to agree about
when they're done. You're asking for send-on-closed-channel
as that communication, but it's a fairly weak one, and it means
that the channel stops being useful when one sender thinks
everything is done. You more typically want to wait until all
senders think everything is done.
> It seems like, with more complex relationships between producer and
> consumer, developers can't safely close channels without other
> synchronization on top, which defeats the point.
Most of the time you don't even have to worry about this.
When you do, being able to detect a send on a closed
channel would not cover all the cases you'd want to implement
anyway. If you really need communication between the senders,
you should communicate between the senders. There's no
silver bullet here.
Russ
Isn't there still a race condition here?