Closing closed channels

Jean-François Bustarret
Random Go tips
Published in
1 min readOct 4, 2016

A Go channel cannot be closed twice, doing so will panic…

It is obviously better to have a single path managing the lifecycle of a channel, creating the channel at the beginning and closing it at the end, but channels enable interesting signaling patterns where multiple closing of a single channel may occur.

A junior developer would probably add a boolean field, but a better way would be to add a simple select call :

The select clause is evaluated top to bottom. If the channel is closed, the first case is non blocking and gets executed. If not, the default clause is triggered and the channel will be closed.

But… is it goroutine safe ? Not really. The channel can still be closed twice when two goroutines evaluate the select clause at the same time.

Adding a mutex would be pretty awkward, the select pattern should be used only with a single goroutine. With multiple goroutines, sync.Once would be a better solution :

--

--