【发布时间】:2018-08-05 19:37:53
【问题描述】:
我想用多个 go 例程异步执行一些事情。我传入用于异步处理文件的“线程”数量。这些文件是要处理的字符串数组。
queue := make(chan string)
threadCount := c.Int("threads")
if c.Int("threads") < len(files) {
threadCount = len(files)
}
log.Infof("Starting %i processes", c.Int("threads"))
for i := 0; i < threadCount; i++ {
go renderGoRoutine(queue)
}
for _, f := range files {
queue <- f
}
close(queue)
而例程本身看起来是这样的:
func renderGoRoutine(queue chan string) {
for file := range queue {
// do some heavy lifting stuff with the file
}
}
只要我只使用一个线程,它就可以正常工作。只要我多取一个,它就会在完成所有 go 例程之前退出/离开范围。
如何让它处理所有内容?
【问题讨论】:
-
每个 goroutine 处理整个队列。这就是你想要的吗?
-
不是每个文件都应该由一个例程处理。他们不写信给频道。文件使用 shell 命令处理。