英文:
[Golang]communication between 2 goroutine
问题
为什么在这个脚本中,goroutine "shower" 不起作用?
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
}
}
在这个脚本中,shower 函数是一个无限循环,它从通道 c 中接收数据并打印出来。然而,在主函数中,我们没有等待 shower 函数完成,而是直接退出了程序。因此,shower 函数没有足够的时间来执行。要解决这个问题,你可以在主函数的末尾添加一个延迟,以等待 shower 函数完成执行。例如,可以使用 time.Sleep 函数来添加一个延迟:
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
go producer(ch)
go shower(ch)
for i := 0; i < 10; i++ {
fmt.Printf("main: %d\n", i)
}
time.Sleep(time.Second) // 添加延迟
}
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
}
}
这样,主函数会等待一秒钟,给足够的时间让 shower 函数执行完毕。
英文:
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
}
}
答案1
得分: 4
你的主函数在goroutine有机会完成它们自己的工作之前就提前退出了。
在结束main()(停止整个程序)之前,你需要等待它们完成,可以使用sync.WaitGroup,就像在“等待n个goroutine终止”中所示。
在你的情况下,你需要等待goroutine shower() 结束:传递一个 wg *sync.WaitGroup 实例给 shower(),当它完成处理时,shower() 会通过 wg.Done() 发出信号。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论