36 lines
479 B
Go
36 lines
479 B
Go
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)
|
|
}
|