如何阻止主要功能并允许goroutines通过通道进行通信,以下代码示例会引发错误
0fatal错误:所有goroutine都睡着了 - 死锁!
echo $?
答案 0 :(得分:1)
我认为您要打印所有值[0:99]
。然后你需要在go routine
中进行循环。
而且,您需要将信号传递给中断循环
func main() {
ch := make(chan int)
stopProgram := make(chan bool)
go func() {
for i := 0; i < 100; i++ {
value := <-ch
fmt.Println(value)
}
// Send signal through stopProgram to stop loop
stopProgram <- true
}()
go func() {
for i := 0; i < 100; i++ {
time.Sleep(100 * time.Millisecond)
ch <- i
}
}()
// your problem will wait here until it get stop signal through channel
<-stopProgram
}