如何用 Go 中的通道替换 goroutines 循环

How to replace goroutines loop by channels in Go

我有一个循环,每次迭代我都有一个我应该处理的新频道源。好的,最好显示我的代码。我有文件列表,每个文件我都想拖尾(比如 tail -f)。我正在使用 github.com/ActiveState/tail 包。

for _, tailFile := range files {
    t, _ := tail.TailFile(tailFile, c)

    // Goroutine per tailing file
    go func() {
        for line := range t.Lines { // t.Lines is a channel
            // Do some magic here
        }
    }()
}

我可以有数千个文件,我想 运行 我的尾巴并行。如您所见,我的程序将有数千个 goroutine。这个循环可以改为只有 1 个 goroutine 的通道吗?

您会在博客 post pipelines.

中找到类似的方法(每个文件一个 goroutine)

The MD5All implementation in parallel.go starts a new goroutine for each file. In a directory with many large files, this may allocate more memory than is available on the machine.

We can limit these allocations by bounding the number of files read in parallel. In bounded.go, we do this by creating a fixed number of goroutines for reading files.
Our pipeline now has three stages: walk the tree, read and digest the files, and collect the digests.

如果您发现自己受到过多 goroutine 分配的内存的限制,您可以组织自己的代码以使用有限数量的 goroutine。 (goroutine 本身很便宜,但是分配给“魔法”部分的内存可能很大)