2 回答
TA贡献1775条经验 获得超11个赞
听起来你需要一个工作池。这是我刚刚写的一个例子:https: //play.golang.org/p/NRM0yyQi8X
package main
import (
"fmt"
"sync"
"time"
)
type Leaf struct {
// Whatever
}
func worker(i int, wg *sync.WaitGroup, in <-chan Leaf) {
for leaf := range in {
time.Sleep(time.Millisecond * 500)
fmt.Printf("worker %d finished work: %#v\n", i, leaf)
}
fmt.Printf("worker %d exiting\n", i)
wg.Done()
}
func main() {
var jobQueue = make(chan Leaf)
var numWorkers = 10
// the waitgroup will allow us to wait for all the goroutines to finish at the end
var wg = new(sync.WaitGroup)
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go worker(i, wg, jobQueue)
}
// enqueue work (this goes inside your tree traversal.)
for i := 0; i < 100; i++ {
jobQueue <- Leaf{}
}
// closing jobQueue will cause all goroutines to exit the loop on the channel.
close(jobQueue)
// Wait for all the goroutines to finish
wg.Wait()
}
TA贡献1943条经验 获得超7个赞
我强烈建议从上到下阅读这篇优秀的博客文章:
https://blog.golang.org/pipelines
它不仅涵盖了您所需要的示例(即并行文件树遍历计算 MD5 文件校验和),还涵盖了更多内容:
扇入/扇出通道技术
并行性
通过完成通道取消管道
通过错误通道进行流水线错误链接
有界并行
最后一个主题,有界并行,用于确保“行走”的大节点目录树不会创建过多的 go-routines:bounded.go
- 2 回答
- 0 关注
- 146 浏览
添加回答
举报