[Golang] 2 goroutine之间的沟通

时间:2014-09-20 08:00:06

标签: go channel goroutine

为什么在该脚本中http://play.golang.org/p/Q5VMfVB67- goroutine淋浴不起作用?

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

1 个答案:

答案 0 :(得分:4)

在goroutines有机会完成自己的工作之前,你的主要功能退出方式。

在结束main()(停止所有程序)之前,您需要等待它们完成,例如sync.WaitGroup,如“Wait for the termination of n goroutines”中所示。

在您的情况下,您需要等待goroutine shower()结束:传递wg *sync.WaitGroup个实例,shower()在完成处理时发出wg.Done()信号。