使用通道来调度任务以进行例程

Using a channel for dispatching tasks to go routine

我正在编写一个程序来渲染图表。 Todo 所以我正在搜索所有文件并希望将它们异步分派到 go 例程以并行处理它们。但是我想我误解了渠道的概念。

files := umlFiles("uml") // list of strings

queue := make(chan string)
for i := 0; i < 4; i++ {
    go func(queue chan string) {
        file, ok := <-queue
        if !ok {
            return
        }

        exec.Command("some command", file).Run()
    }(queue)
}
for _, f := range files {
    queue <- f
}
close(queue)

这将 运行 在处理完前 4 个文件后陷入死锁,但不会继续处理其余文件。

我可以使用通道将任务分派给 运行ning go 例程并在所有任务完成后停止它们吗?如果是这样,上面的代码有什么问题?

曾经到达这里:
how-to-stop-a-goroutine

你们很亲近。你遇到的问题是你正在启动 4 个 goroutines,它们都做 1 件工作,然后 return。试试这个

for i := 0; i < 4; i++ {
    go func(queue chan string) {
        for file := range queue {
            exec.Command("some command", file).Run()
        }
    }(queue)
}

一旦队列关闭,这些将 return。