Middle+
Task 4: Find errors in code with channels and goroutines (double closing of a channel)
sobes.tech AI
Answer from AI
A double channel close error in Go occurs when the same channel is closed more than once, leading to a panic.
A typical example of this error:
dataCh := make(chan int)
// Goroutine that closes the channel
go func() {
for i := 0; i < 5; i++ {
dataCh <- i
}
close(dataCh) // Closing the channel
}()
// Trying to close the channel elsewhere again
close(dataCh) // PANIC: closing an already closed channel
How to avoid:
- Only the sender (writer) should close the channel.
- Receivers should not close the channel.
- If multiple goroutines write to the channel, synchronization of closing (e.g., using sync.WaitGroup) is necessary.
Example of correct usage:
func producer(ch chan<- int) {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch) // Close the channel only here
}
func consumer(ch <-chan int) {
for val := range ch {
fmt.Println(val)
}
}
func main() {
ch := make(chan int)
go producer(ch)
consumer(ch)
}
Thus, to avoid double closing, it is essential to clearly define responsibility for closing the channel and use synchronization when necessary.