Sobes.tech
Junior — Middle

Is it possible to close one channel from multiple goroutines simultaneously?

sobes.tech AI

Answer from AI

No, it is not possible to close the same channel from multiple goroutines simultaneously. In Go, a channel must be closed exactly once, and usually this is done by the goroutine responsible for sending data to the channel.

If multiple goroutines attempt to close the channel, it will cause a panic (runtime panic).

The correct approach:

  • Identify a single goroutine responsible for closing the channel.
  • Use additional synchronization mechanisms (for example, sync.Once) to ensure that the close operation happens only once.

Example with sync.Once:

var once sync.Once

func closeChannel(ch chan int) {
    once.Do(func() {
        close(ch)
    })
}

Thus, even if multiple goroutines call closeChannel, the channel will be closed only once.