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 文件校驗和),還涵蓋了更多內容:
扇入/扇出通道技術
并行性
通過完成通道取消管道
通過錯誤通道進行流水線錯誤鏈接
有界并行
最后一個主題,有界并行,用于確?!靶凶摺钡拇蠊濣c目錄樹不會創建過多的 go-routines:bounded.go
- 2 回答
- 0 關注
- 175 瀏覽
添加回答
舉報