等待所有项目添加到缓冲通道



我已经实现了 WaitGroup,但它没有按预期工作,我需要打印所有 1000 个日志,但实际结果只是 ~9xx 日志,我知道根本原因是第一个路由尚未完成,而缓冲通道循环中的其余 goroutines 已经完成

如何解决此问题?提前致谢

package main
import (
"log"
"sync"
)
func main() {
buffer := make(chan int, 5)
var wg sync.WaitGroup
wg.Add(1)
go func(wg *sync.WaitGroup) {
for i := 1; i <= 1000; i++ {
buffer <- i
}
close(buffer)
wg.Done()
}(&wg)
for item := range buffer {
wg.Add(1)
go func(wg *sync.WaitGroup, item int) {
log.Printf("done for item %dn", item)
wg.Done()
}(&wg, item)
}
wg.Wait()
}

更新

我发现了问题,我在GoLand IDE中运行代码,它没有打印所有日志,如果我在终端中运行,应该没问题

我没有看到等待组有任何问题,它正在 go 操场上打印所有 1000 个日志。

但它已经在发生。

由于它没有正确排序,我认为它会误导您认为它只打印 ~9xx 日志。

我运行它并得到(未显示完整输出(:

2020/06/03 10:38:35 done for item 986
2020/06/03 10:38:35 done for item 988
2020/06/03 10:38:35 done for item 1000
2020/06/03 10:38:35 done for item 995
2020/06/03 10:38:35 done for item 993
2020/06/03 10:38:35 done for item 996
2020/06/03 10:38:35 done for item 997
2020/06/03 10:38:35 done for item 991
2020/06/03 10:38:35 done for item 998
2020/06/03 10:38:35 done for item 990
2020/06/03 10:38:35 done for item 992
2020/06/03 10:38:35 done for item 999
2020/06/03 10:38:35 done for item 989
2020/06/03 10:38:35 done for item 412

注意:1000 在那里。

如果要确认:

go run main.go &> sample.txt // Redirects the output of the executable to sample.txt
cat sample.txt | wc -l       // Counts the number of lines in output

是1000。

最新更新