/** * @Author: zhangsan * @Description: * @File: num * @Version: 1.0.0 * @Date: 2020/12/8 上午9:42 */ package main import ( "fmt" "runtime" "sync" "time" ) type Golimit struct { n int c chan struct{} } // initialization Glimit struct func New(n int) *Golimit { return &Golimit{ n: n, c: make(chan struct{}, n), } } // Number of released goroutines func (g *Golimit) Released(n int) { if n > g.n { g.c = make(chan struct{}, 1) } else { g.c = make(chan struct{}, g.n-n+1) } } // Run f in a new goroutine but with limit. func (g *Golimit) Run(f func()) { g.c <- struct{}{} go func() { f() <-g.c }() } var wg = sync.WaitGroup{} func main() { number := 10 g := New(5) g.Released(6) //释放协程数量 //os.Exit(1) for i := 0; i < number; i++ { wg.Add(1) value := i goFunc := func() { // 做一些业务逻辑处理 fmt.Printf("go func: %d\n", value) time.Sleep(time.Second) wg.Done() } g.Run(goFunc) } fmt.Println(runtime.NumGoroutine()) wg.Wait() }