为什么 goroutines 不处理同一个文件两次?

Why doesn't the goroutines process the same file twice?

我正在查看 goroutines 博客 post 关于 goroutines 和通道等的模式

bounded.go 示例中,我看到了这个:

    paths, errc := walkFiles(done, root)

    // Start a fixed number of goroutines to read and digest files.
    c := make(chan result) // HLc
    var wg sync.WaitGroup
    const numDigesters = 20
    wg.Add(numDigesters)
    for i := 0; i < numDigesters; i++ {
        go func() {
            digester(done, paths, c) // HLc
            wg.Done()
        }()
    }

既然每个摘要器都在处理相同的 paths 集合,为什么它不重复同一个文件两次?

walkFiles,它没有在您的问题中重现,但它是理解它的关键,具有以下签名:

func walkFiles(done <-chan struct{}, root string) (<-chan string, <-chan error)

所以在您引用的代码中,paths 不是 "collection"(即切片),而是 通道 。当每个工作人员从通道中读取时,它会将下一条路径拉出通道。下一个从通道接收的 worker 不会得到相同的路径,它会得到下一个。

digester 的所有三个参数都是频道:

func digester(done <-chan struct{}, paths <-chan string, c chan<- result) 
  • done 用于指示工作人员他们应该停止,即使还有工作在排队。
  • paths 是工人从中接收路径的工作队列。
  • c是工作人员发送结果的渠道。