why in this case it is a dedlock on the line #23 (<- done)
package main
func main() {
c := make(chan int)
done := make(chan bool)
go func() {
for i := 0; i < 50; i++ {
c <- i
}
done <- true
}()
go func() {
for i := 0; i < 50; i++ {
c <- i
}
done <- true
}()
<- done
<- done
close(c)
for i := range c {
println(i)
}
}
but in this case there is no deadlock
package main
import "time"
func main() {
c := make(chan int)
go func() {
for i := 0; i < 50; i++ {
<- c
}
}()
time.Sleep(time.Second * 5)
}
also why there is no deadlock when main thread is sleeping?
c is unbuffered and will not accept a second item before the first was read. As you never read from c, no loop will ever succeed to finish so there is never something sent to done.
Because you don’t have a done channel there that you wait for. Your main go routine just exits after 5 seconds and does not care for the status of its children.