duankuai6586 2019-01-10 23:27
浏览 46
已采纳

退出前如何确保goroutine完全运行

I have a function calling a go routine that calls additional functions within it. However, those go routines are exiting before being completely finished. How would I make sure all the underlying code within the function (migrateUserHelper) runs before the exit. Here is my code below:

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

Im trying to update A LOT OF records in the database simultaneously in different go routines.

Thanks

  • 写回答

1条回答 默认 最新

  • doushenyi9104 2019-01-10 23:39
    关注

    The WaitGroup is a counting semaphore and can be used to count off goroutines as they finish their work, but for that, you need to set how many goroutines you are going to spawn. You can do that by calling the method 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))
    }
    

    playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计