go语言channel的一个疑问

下面的代码

func main () {
    c1 := make(chan [0]int)
    
    c1 <- [0]int{}
    b := <-c1

    fmt.Println(b)
}

会报错,fatal error: all goroutines are asleep - deadlock!

但是如果这样写就没问题

func main () {
    c1 := make(chan [0]int)

    go func() {
        c1 <- [0]int{}
    }()

    b := <-c1

    fmt.Println(b)
}

也就是说,如果在主协程里往管道输入并且在主协程里输出的话,会报死锁。但是如果在子协程里面往管道里面写然后再主协程里面读取的话就没问题,这一点让我很疑惑还请各位大佬帮忙解释一下

阅读 2.3k
1 个回答

没有 buffer 的 channel 必须同时有人读写的,读写操作才能继续,否则就会等待。

读写写在同一个 goroutine ,没办法做到同时。于是在第一个写就等待锁住了,因为没有人读;然后读语句没有执行机会。


Receive Operator

For an operand ch of channel type, the value of the receive operation <-ch is the value received from the channel ch. The channel direction must permit receive operations, and the type of the receive operation is the element type of the channel. The expression blocks until a value is available. Receiving from a nil channel blocks forever. A receive operation on a closed channel can always proceed immediately, yielding the element type's zero value after any previously sent values have been received.

Send Statement

Send statements

Both the channel and the value expression are evaluated before communication begins. Communication blocks until the send can proceed. A send on an unbuffered channel can proceed if a receiver is ready. A send on a buffered channel can proceed if there is room in the buffer. A send on a closed channel proceeds by causing a run-time panic. A send on a nil channel blocks forever.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题