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))
}
操场。
- 1 回答
- 0 关注
- 97 浏览
添加回答
举报