On 7 November 2017 at 00:59, Albert Tedja <
nicho...@gmail.com> wrote:
> So, I just found out that closed channels always yield the zero value. That
> means, a closed channel inside a select statement seems to always be
> guaranteed to be executed.
>
> Since closing an already closed channel creates a panic, does this mean then
> I can do this to make sure that the channel is closed only once?
>
>
> select {
> case <- closedchan:
> default:
> close(closedchan)
> }
You can do that if you wrap it in a mutex so that nothing else
can be doing the same thing at the same time. That's
a common workaround for the fact that sometimes you want
to be able to close a signal-only channel (chan struct{}) from
a Close method that might be called multiple times.
Another possibility might be to do this:
func closeChan(c chan struct{}) {
defer func() {
// Catch the panic from closing an already-closed channel.
recover()
}()
close(c)
}