限制协程使用数量

不限制的时候,有多少业务开多少协程

func job(index int) {
    time.Sleep(time.Millisecond * 500)
    fmt.Println(index)
}

func main() {
    wg := sync.WaitGroup{}
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(index int) {
            defer wg.Done()
            job(index)
        }(i)
    }
    wg.Wait()
}

限制协程

var pool chan struct{}

func job(index int) {
    time.Sleep(time.Millisecond * 500)
    fmt.Println(index)
}

func main() {
    wg := sync.WaitGroup{}
    pool = make(chan struct{}, 10)

    for i := 0; i < 100; i++ {
        wg.Add(1)
        pool <- struct{}{}

        go func(index int) {
            defer wg.Done()
            defer func() {
                <-pool
            }()
            job(index)
        }(i)
    }
    wg.Wait()
}

或者

var pool chan struct{}

func job(index int, pool <-chan struct{}) {
    defer func() {
        <-pool
    }()
    time.Sleep(time.Millisecond * 500)
    fmt.Println(index)
}

func main() {
    wg := sync.WaitGroup{}
    pool = make(chan struct{}, 10)

    for i := 0; i < 100; i++ {
        wg.Add(1)
        pool <- struct{}{}

        go func(index int) {
            defer wg.Done()
            job(index, pool)
        }(i)
    }
    wg.Wait()
}

结果就变成分批打印了,达到限制的效果

你可能感兴趣的:(限制协程使用数量)