Slide 41
Slide 41 text
func distributedSum(numOfWorkers int, from int, to int) int {
wg := &sync.WaitGroup{}
wg.Add(numOfWorkers)
in := make(chan int, (to-from)-1)
out := make(chan int, numOfWorkers)
res := make(chan int, 1)
for i := 0; i < numOfWorkers; i++ {
go sumWorker(in, out, wg)
}
go compilationWorker(out, res)
for i := 0; i <= to; i++ {
in <- i // 塞資料給各個 sumWorkers
}
close(in) // 關閉資料窗⼝ (通知各個 sumWorkers 停⽌讀值)
wg.Wait() // 等待所有 workers 結束
close(out) // 關閉資料窗⼝ (通知 compilationWorker 停⽌讀值)
return <-res
}