[Golang]communication between 2 goroutine

Issue

why in that script http://play.golang.org/p/Q5VMfVB67-
goroutine shower doesn’t work ?

package main

import "fmt"

func main() {
    ch := make(chan int)
    go producer(ch)
    go shower(ch)
    for i := 0; i < 10; i++ {
        fmt.Printf("main: %d\n", i)
    }
}
func shower(c chan int) {
    for {
        j := <-c
        fmt.Printf("worker: %d\n", j)
    }
}
func producer(c chan int) {
    for i := 0; i < 10; i++ {
        c <- i
    }
}

Solution

Your main function exit way before the goroutines have a chance to complete their own work.

You need to wait for them to finish before ending main() (which stops the all program), with for instance sync.WaitGroup, as seen in “Wait for the termination of n goroutines“.

In your case, you need to wait for goroutine shower() to end: pass a wg *sync.WaitGroup instance, for shower() to signal wg.Done() when it finishes processing.

Answered By – VonC

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.