我有以下功能:如何進行並行通用去治療?
func myrun(entries []WhatEverType) {
for i := range entries {
dotreatment(entries[i])
}
}
我要讓並行調用dotreatment,我試過如下:
func myrunMT(entries []WhatEverType) {
var wg sync.WaitGroup
stopped := false
threads := 5 //number of threads could be argument
com := make(chan WhatEverType, 100) //size of chan could be argument
wg.Add(threads)
for i := 0; i < threads; i++ {
go func() {
for !stopped || len(com) {
select {
case entry := <-com:
dotreatment(entry) //lock if necessary
case time.After(100*time.Millisecond):
}
}
wg.Done()
}()
}
for _, entry := range entries {
com <- entry
}
stopped = true
wg.Wait()
}
有沒有更好的辦法做到這一點?特別是我想避免通過一個陳發送所有條目,並且只在共享程序之間使用共享索引。
如果你有一般需要做並行工作,將控制節流並行「線程」數量的批生產,則可以像這樣使用(或複製)'code.cloudfoundry.org/workpool'包:https://play.golang.org/p/XKbT67vP6i(注意,這實際上並不在遊樂場中運行,因爲它導入了一個外部包)。 –