Search code examples
gochannelgoroutine

Not receiving in the golang channel


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
   $

Solution

  • 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)
            }
    }