简体   繁体   English

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

[英]How to replace goroutines loop by channels in Go

I have a loop, for each iteration I have a new channel source, that I should handle. 我有一个循环,对于每次迭代,我都会处理一个新的通道源。 Ok, it's better to show my code. 好的,最好显示我的代码。 I have list of files, each file I want to tail (like tail -f). 我有文件列表,每个文件都想拖尾(例如tail -f)。 I am using github.com/ActiveState/tail package. 我正在使用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
        }
    }()
}

I can have thousands of files and I want to run my tail in parallel. 我可以有成千上万个文件,并且希望并行运行。 As you see my program will have thousands of goroutines. 如您所见,我的程序将包含数千个goroutine。 Can this loop be changed to channels, with only 1 goroutine? 可以仅使用一个goroutine将此循环更改为通道吗?

You will find a similar approach (one goroutine per file) in the blog post pipelines . 您会在博客帖子管道中找到类似的方法(每个文件一个goroutine)。

The MD5All implementation in parallel.go starts a new goroutine for each file. 在MD5All实施parallel.go开始为每个文件一个新的goroutine。 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. bounded.go ,我们通过创建固定数量的goroutine来读取文件来执行此操作。
Our pipeline now has three stages: walk the tree, read and digest the files, and collect the digests. 现在,我们的管道包括三个阶段:走树,读取和消化文件以及收集摘要。

You could organize your own code to use a limited number of goroutines, if you find yourself limited by memory allocated by a too large number of goroutines. 如果发现自己受到太多goroutine分配的内存的限制,则可以组织自己的代码以使用有限数量的goroutine。 (the goroutine itself is cheap, but the memory allocated for the "magic" part can be big) (goroutine本身很便宜,但是分配给“魔术”部分的内存可能很大)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM