package main import ( "fmt" ) func main() { ch := make(chan string) for i := 0; i <= 5; i++ { go printHelloWorld(i, ch) } for { if msg,ok := <-ch;ok{ fmt.Println(msg) }else{ break } } } func printHelloWorld(i int, ch chan string) { ch <- fmt.Sprintf("hello world %d\n", i) }
老师:为什么我这段代码输出会有个
fatal error: all goroutines are asleep - deadlock!
报错呢?
改成这样就可以了:
ch没有关闭,一直在等待。
package mainimport ( "fmt")func main() { ch := make(chan string) for i := 0; i <= 5; i++ { go printHelloWorld(i, ch) } for i := 0; i <= 5; i++ { fmt.Println(<-ch) }}func printHelloWorld(i int, ch chan<- string) { ch <- fmt.Sprintf("hello world %d\n", i)}