第二个通道即使独立也会造成死锁

时间:2014-09-22 02:50:29

标签: concurrency go goroutine

这是来自this other post

的更多问题

我不明白为什么添加第二个频道(在我的情况下为c2)会导致死锁。频道是独立的,我不明白为什么c2应该被阻止

Link to playground

func do_stuff(done chan bool) {
    fmt.Println("Doing stuff")
    done <- true
}

func main() {
    fmt.Println("Main")
    done := make(chan bool)
    go do_stuff(done)
    <-done
    //Up tp here everything works
    c2 := make(chan int)
    c2 <- 1
    fmt.Println("Exit ",<-c2)

}

2 个答案:

答案 0 :(得分:4)

  

The Go Programming Language Specification

     

Send statements

     

通信阻止,直到发送可以继续。发送一个   如果接收器准备好,可以继续进行无缓冲的通道。

没有接收器就绪。

package main

func main() {
    c2 := make(chan int)
    c2 <- 1
}

输出:

fatal error: all goroutines are asleep - deadlock!

答案 1 :(得分:2)

陈述

c2 := make(chan int)
c2 <- 1

总会阻止。 Link to Playground

由于通道c2未缓冲,因此在另一个goroutine从通道接收到值之前,发送操作无法继续。没有goroutine可以从频道接收,因此发送块永远阻止。

channels section in Effective Go是阅读无缓冲频道的好地方。另请参阅频道部分并发送Go Language Specification

如果您将c2设为缓冲频道,该程序将按照我的预期运作:

    c2 := make(chan int, 1)

通过此更改,发送可以在不与接收器同步的情况下继续进行。

Link to Playground

相关问题