限制协程执行数量的基本方法
2023-01-17 本文已影响0人
我爱张智容
func job(i int) {
fmt.Println(i)
time.Sleep(time.Second)
}
func main() {
maxNum := 10
pool := make(chan struct{}, maxNum) // 协程池
wg := sync.WaitGroup{}
for i := 0; i < 100; i++ {
pool <- struct{}{}
wg.Add(1)
go func(i int) {
defer wg.Done()
defer func() {
<-pool
}()
job(i)
}(i)
}
}