Why is this a deadlock in example 1, and does not deadlock nor print anything in example 2 ?
Example 1.)
func main() {
w := sync.WaitGroup{}
w.Add(4)
c := make(chan int)
go func() { c <- 1; w.Done() }()
go func() { c <- 2; w.Done() }()
go func() { c <- 3; w.Done() }()
go func() { println(len(c)); w.Done() }()
w.Wait()
}
Example 2.)
func main() {
w := sync.WaitGroup{}
w.Add(3)
c := make(chan int)
go func() { c <- 1; w.Done() }()
go func() { c <- 2; w.Done() }()
go func() { c <- 3; w.Done() }()
go func() { w.Wait(); println(len(c)) }()
}
In the first example, the channels won't be able to send since there is no receiver on the other end of the unbuffered channel. The sent will block forever. And therefore the waitgroup will wait forever. This is a deadlock situation as your program is not able to continue at all.
In the second case, the same thing happens, but you wait in a separate goroutine. So the main function is able to continue. It's not a complete deadlock. In this case, the continuation means the program just exists.