dongyuqi3808
dongyuqi3808
2017-08-24 17:17

在golang频道中未收到

已采纳

In the example below I am sending "ping"s to 'mq' string channel in anonymous go routine and try to receive these strings in four dequeue() goroutines , not sure why it doesn't print anything

    $ cat channels2.go 
    ...
    var mq chan string

    func main() {
            mq = make(chan string)
            for i := 0; i < 4; i++ {
                    go dequeue()
            }
            go func() {
                    for i := 0; ; i++ {
                            mq <- "ping" 
                            }
            }()

    }

    func dequeue() {
            for m := range mq {
                    fmt.Println(m)
            }
    }
   $ go run channels2.go
   $
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dqyanc7264 dqyanc7264 4年前

    As soon as the main goroutine returns, the program exits. So you need to make sure to not return from main early. One way to do this is to execute the write-loop to the channel in the main goroutine:

    var mq chan string
    
    func main() {
            mq = make(chan string)
            for i := 0; i < 4; i++ {
                    go dequeue()
            }
            for {
                mq <- "ping" 
            }
    }
    
    func dequeue() {
            for m := range mq {
                    fmt.Println(m)
            }
    }
    
    点赞 评论 复制链接分享