1 回答
TA貢獻1794條經驗 獲得超8個贊
我認為最好的方法是保留一個工作 goroutine 池,在通道中為它們分派工作,然后關閉通道以便它們退出。
像這樣:
// create a channel for work "tasks"
ch := make(chan string)
wg := sync.WaitGroup{}
// start the workers
for t := 0; t < 100; t++{
wg.Add(1)
go saveToDB(ch, &wg)
}
// push the lines to the queue channel for processing
for _, line := range fileline {
ch <- line
}
// this will cause the workers to stop and exit their receive loop
close(ch)
// make sure they all exit
wg.Wait()
然后 saveFunction 看起來像這樣:
func saveToDB(ch chan string, wg *sync.WaitGroup) {
// cnosume a line
for line := range ch {
// do work
actuallySaveToDB(line)
}
// we've exited the loop when the dispatcher closed the channel,
// so now we can just signal the workGroup we're done
wg.Done()
}
- 1 回答
- 0 關注
- 178 瀏覽
添加回答
舉報
