我想在goroutines和无限期阻止主线程之间进行通信

时间:2018-02-07 15:37:06

标签: go goroutine channels

如何阻止主要功能并允许goroutines通过通道进行通信,以下代码示例会引发错误

0fatal错误:所有goroutine都睡着了 - 死锁!

echo $?

1 个答案:

答案 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
}
相关问题