add: waitgroup的几种用法
This commit is contained in:
parent
c885d0189a
commit
acadb8457f
35
waitgroup/example2/main.go
Normal file
35
waitgroup/example2/main.go
Normal 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)
|
||||
}
|
1
waitgroup/example2/readme.md
Normal file
1
waitgroup/example2/readme.md
Normal file
@ -0,0 +1 @@
|
||||
> 用waitgroup限制并发数量的用法
|
Loading…
Reference in New Issue
Block a user