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

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

如何確保 goroutine 在退出前完全運行

如何確保 goroutine 在退出前完全運行

Go
隔江千里 2023-06-01 14:32:56
我有一個調用 go 例程的函數,該例程調用其中的其他函數。然而,那些go例程在完全完成之前就已經退出了。我如何確保函數 (migrateUserHelper) 中的所有底層代碼在退出之前運行。下面是我的代碼:func MigrateUsers(){  var wg sync.WaitGroup  userCount:=10 //userDAO.GetUserCount()  limitSize:=2  count:=0  divisor = userCount/limitSize  for divisor>0{      wg.Add(1)      go migrateUserHelper(limitSize,&wg,count)      divisor =divisor -1      count=count +1  }  wg.Wait()  fm.Println("DONE BATCHES") } func migrateUserHelper(limitSize int, count int, wg *sync.WaitGroup)  {   defer wg.Done()   fmt.Println("Start batch "+strconv.Itoa(count))   users:= userDAO.GetUsers(limitSize)   fmt.Println("Fetched Users for batch "+ strconv.Itoa(count))   userDAO.BulkUpdateUsers(users)  fmt.Println("Reconciled Users for batch "+ strconv.Itoa(count))}我試圖在不同的 go 例程中同時更新數據庫中的大量記錄。
查看完整描述

1 回答

?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

WaitGroup是一個計數信號量,可用于在 goroutine 完成工作時對其進行計數,但為此,您需要設置要生成的 goroutine 數量。您可以通過調用方法Add來做到這一點:

package main


import (

? ? "fmt"

? ? "strconv"

? ? "sync"

)


func main() {

? ? migrateUsers()

}


func migrateUsers() {

? ? var wg sync.WaitGroup


? ? userCount := 10

? ? limitSize := 2

? ? count := 0

? ? divisor := userCount / limitSize

? ? wg.Add(divisor)


? ? for divisor > 0 {

? ? ? ? go migrateUserHelper(limitSize, count, &wg)

? ? ? ? divisor = divisor - 1

? ? ? ? count = count + 1

? ? }


? ? wg.Wait()

? ? fmt.Println("DONE BATCHES")

}


func migrateUserHelper(limitSize int, count int, wg *sync.WaitGroup) {

? ? defer wg.Done()

? ? fmt.Println("Start batch " + strconv.Itoa(count))

? ? fmt.Println("Fetched Users for batch " + strconv.Itoa(count))

? ? fmt.Println("Reconciled Users for batch " + strconv.Itoa(count))

}

操場。



查看完整回答
反對 回復 2023-06-01
  • 1 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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