dongyuqi3808 2017-08-24 17:17
浏览 61
已采纳

在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条回答 默认 最新

  • 普通网友 2017-08-24 17:21
    关注

    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)
            }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?