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 關注
- 130 瀏覽
添加回答
舉報