限制协程最大并发数

func MulProduction() {
    concurrency := make(chan struct{}, 100) //控制最大协程数
    wg := sync.WaitGroup{}
    defer close(concurrency)
    for id := 0; id < 100; id++ {
        wg.Add(1)
        concurrency <- struct{}{}
        go production(id, &wg, concurrency)
    }

    wg.Wait()
}

func production(id int, wg *sync.WaitGroup, concurrency <-chan struct{}) {
    defer func() {
        wg.Done()
        <-concurrency
    }()
    fmt.Println("production id:", id)
}

 

posted @ 2023-08-01 10:53  知道了呀~  阅读(19)  评论(0编辑  收藏  举报