为什么在那个脚本中,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
}
}发布于 2014-09-20 08:03:28
你的主要功能退出之前,猩猩有机会完成他们自己的工作。
您需要在结束main() (停止所有程序)之前等待它们完成,例如,sync.WaitGroup,如"Wait for the termination of n goroutines“中所示。
在您的示例中,您需要等待goroutine shower()结束:传递一个wg *sync.WaitGroup实例,在shower()完成处理时向wg.Done()发送信号。
https://stackoverflow.com/questions/25946603
复制相似问题