c := make(chan int)
for i := 0; i < 10; i++ {
go func() {
for j := 0; j < 10; j++ {
c <- j
}
}()
}
//Always a deadlock at the end while using range clause.
//close(c) also didn't work
for range c {
fmt.Println(<-c)
}
// But this works fine. Why??
for k := 0; k < 100; k++ {
fmt.Println(<-ch)
}
The for k := 0; k < 100; k++ loop runs 100 times and reads 100 values from the channel - this is okay.
The for range c loop runs endlessly and consumes all the values from the channel until all the go-routines are finished. It continues to read from the empty channel as the only routine left which raises the deadlock.