2017-05-27 11:44


  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术

I am coming upto speed on channels in golang. Per its documentation,

Channels are a typed conduit through which you can send and receive values with the channel operator, <-.

I get that. I understand how it is used from examples that utilize go routines. I tried an extremely trivial example. It results in a deadlocked program. Ignoring the pointlessness of this program can you please tell me why this is deadlocked?

package main
import  "fmt"
func main() {
    c := make(chan int)
    c <- 17
    fmt.Println(<- c)

The referenced documentation adds that

By default, sends and receives block until the other side is ready.

OK, in the above example, the sender (the main routine) is ready to send when c <- 17 is encountered. So shouldn't that execute. Subsequently the Println should be able to drain the channel.

I realize everything works fine if c <- 17 is replaced by

go func() { c <- 17 } ()

Just trying to understand why that's necessary.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享