channel死锁
package main
import "fmt"
func main() {
ch := make(chan string)
for i := 0; i < 10; i++ {
s := <- ch
fmt.Println(s)
}
go func(ch chan string) {
for i := 0; i < 10; i++ {
ch <- fmt.Sprintf("%d", i)
}
}(ch)
}
报错
all goroutines are asleep - deadlock!
s := <- ch
解决
思路:先开启一个协程让运行接收端/发送端,main主协程继续往下执行。两个协程(接收断/发送端)都准备好后,就开始传输数据。
package main
import "fmt"
func main() {
ch := make(chan string)
go func(ch chan string) {
for i := 0; i < 10; i++ {
ch <- fmt.Sprintf("%d", i)
}
}(ch)
for i := 0; i < 10; i++ {
s := <- ch
fmt.Println(s)
}
}