This code runs and ends with no deadlock error. Why?
func main() {
ch := make(chan int)
go func() {
ch<-1
ch<-2
}()
time.Sleep(time.Second)
}
This code runs and ends with no deadlock error. Why?
func main() {
ch := make(chan int)
go func() {
ch<-1
ch<-2
}()
time.Sleep(time.Second)
}
The unbuffered channel needs two end points to work, so let's start with correct example:
package main
func main() {
go fun2()
<-ch
<-ch
}
func fun2() {
ch <- 1
ch <- 2
}
var ch = make(chan int)
Here fun2()
sends two values and main()
receives two values.
Your sample code has only one end point so the channel is not correctly constructed, so it is deadlock, but the main
goroutines exits normally so you don't see the error. Here, there is no second end point, so this is deadlock:
package main
func main() {
var ch = make(chan int)
ch <- 1
}
Output:
fatal error: all goroutines are asleep - deadlock!