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

时间:2019-01-10 23:27:11

标签: mongodb go goroutine mgo

我有一个调用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 个答案:

答案 0 :(得分:3)

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

playground

相关问题