← blog
#9ConcurrencyB2

Closing channels

Producer closes the channel, consumer cancels the context.

The safest way to close a channel is to close it from the producer side only. This tells consumers that the producer is finished and they can stop consuming. It saves you from panics like:

  • panic: send on closed channel -> sending to a closed channel panics.
  • panic: close of closed channel -> closing a closed channel also panics.

When you have several producers, none of them closes. Let one coordinator do it: wait for every producer, then close the channel once (wg.Wait() + close(ch)).

And if you need to stop a producer, cancel its context.

A note: closing a channel does not throw away data that is still in the channel!