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

How to make sure goroutine fully runs before exiting

我有一个调用 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 例程中同时更新数据库中的大量记录。

谢谢

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.