mackristof
mackristof

Reputation: 61

[Golang]communication between 2 goroutine

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

Upvotes: 2

Views: 2281

Answers (1)

VonC
VonC

Reputation: 1328712

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.

Upvotes: 4

Related Questions