问题
Can you explain the following error: fatal error:
true
true
all goroutines are asleep - deadlock!
package main
import (
"fmt"
)
func printer(ch chan bool) {
ch <- true
}
func main() {
var c chan bool = make(chan bool, 2)
for i := 0; i < 5; i++ {
go printer(c)
}
for i := range c {
fmt.Println(i)
}
}
回答1:
Because the channel c
is not closed, the range loop does not exit. This code will not block:
func main() {
var c chan bool = make(chan bool, 2)
for i := 0; i < 5; i++ {
go printer(c)
}
for i := 0; i < 5; i++ {
fmt.Println(<-c)
}
}
playground example
来源:https://stackoverflow.com/questions/34572122/fatal-error-all-goroutines-are-asleep-deadlock