add: waitgroup的几种用法

This commit is contained in:
洪晓威 2022-01-25 11:20:56 +08:00
parent c885d0189a
commit acadb8457f
2 changed files with 36 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package main
import (
"fmt"
"strconv"
"sync"
"time"
)
/*
限制并发数量的用法
*/
func main() {
wg := sync.WaitGroup{}
// 最多允许的并发数量
limit := make(chan struct{}, 20)
for i := 0; i < 100; i++ {
wg.Add(1)
limit <- struct{}{}
go func(num int) {
defer func() {
<-limit
wg.Done()
}()
dosth(num)
}(i)
}
wg.Wait()
}
func dosth(i int) {
fmt.Println("do sth-->", strconv.Itoa(i))
// 模拟耗时1s
time.Sleep(time.Second)
}

View File

@ -0,0 +1 @@
> 用waitgroup限制并发数量的用法