goroutine 中的死锁

有人可以给我一些关于这段代码的见解,为什么会出现死锁错误for x:=range c


func main() {

    c:=make(chan int,10)


    for i:=0;i<5;i++{

        go func(chanel chan int,i int){

            println("i",i)

            chanel <- 1

        }(c,i)

    }


    for x:=range c {

        println(x)

    }

    println("Done!")

}


四季花海
浏览 102回答 3
3回答

30秒到达战场

因为这:&nbsp; &nbsp; for x:=range c {&nbsp; &nbsp; &nbsp; &nbsp; println(x)&nbsp; &nbsp; }将循环直到通道c关闭,这在这里从未完成。这是修复此问题的一种方法,即使用 WaitGroup:package mainimport "sync"func main() {&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; c := make(chan int, 10)&nbsp; &nbsp; for i := 0; i < 5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; &nbsp; &nbsp; go func(chanel chan int, i int) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; println("i", i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; chanel <- 1&nbsp; &nbsp; &nbsp; &nbsp; }(c, i)&nbsp; &nbsp; }&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; &nbsp; &nbsp; close(c)&nbsp; &nbsp; }()&nbsp; &nbsp; for x := range c {&nbsp; &nbsp; &nbsp; &nbsp; println(x)&nbsp; &nbsp; }&nbsp; &nbsp; println("Done!")}在 Go Playground 上尝试一下

潇湘沐

您创建五个 goroutine,每个 goroutine 向通道发送一个整数值。一旦所有这五个值都被写入,就没有其他 goroutine 写入通道了。主 goroutine 从通道读取这五个值。但是没有任何 goroutine 可以写入第六个值或关闭通道。因此,您在等待来自通道的数据时陷入僵局。所有写入完成后关闭通道。弄清楚如何使用这段代码来做到这一点应该是一个有趣的练习。

GCT1015

需要关闭通道以指示任务已完成。与a协调sync.WaitGroup:c := make(chan int, 10)var wg sync.WaitGroup // herefor i := 0; i < 5; i++ {&nbsp; &nbsp; wg.Add(1) // here&nbsp; &nbsp; go func(chanel chan int, i int) {&nbsp; &nbsp; &nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; println("i", i)&nbsp; &nbsp; &nbsp; &nbsp; chanel <- 1&nbsp; &nbsp; }(c, i)}go func() {&nbsp; &nbsp; wg.Wait() // and here&nbsp; &nbsp; close(c)}()for x := range c {&nbsp; &nbsp; println(x)}println("Done!")https://play.golang.org/p/VWcBC2YGLvM
打开App,查看更多内容
随时随地看视频慕课网APP