亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

限制運行的并發任務數

限制運行的并發任務數

Go
catspeake 2021-12-13 10:44:17
所以我經常遇到這個問題go。假設我有一個包含 100,000 行文本的文本文件。現在我想將所有這些行保存到數據庫中。所以我會做這樣的事情:file, _ := iotuil.ReadFile("file.txt")fileLines := strings.Split(string(file), "\n")現在我將遍歷文件中的所有行:for _, l := range fileLines{  saveToDB(l)}現在我想saveToDB同時運行這個函數:var wg sync.WaitGroupfor _, l := range fileLines{  wg.Add(1)  go saveToDB(l, &wg)}wg.Wait()我不知道這是否有問題,但那會運行 100,000 個并發函數。有什么辦法可以說嘿,運行 100 個并發函數,等待所有這些都完成,然后再運行 100 個。for i, _ := range fileLine {  for t = 0; t < 100; t++{    wg.Add(1)    go saveToDB(fileLine[i], &wg)  }  wg.Wait()}我需要做類似的事情還是有更干凈的方法來解決這個問題?或者我運行 100,000 個并發任務不是問題?
查看完整描述

1 回答

?
慕田峪9158850

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()

}


查看完整回答
反對 回復 2021-12-13
  • 1 回答
  • 0 關注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號