Golang WaitGroup结合Channel 控制并发数量

package main

import (
    "fmt"
    "sync"
    "time"
)

var wg sync.WaitGroup

func main() {
    userCount := 10
    ch := make(chan int, 5)
    for i := 0; i < userCount; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for d := range ch {
                fmt.Printf("go func: %d, time: %d\n", d, time.Now().Unix())
                time.Sleep(time.Second * time.Duration(d))
            }
        }()
    }

    for i := 0; i < 10; i++ {
        ch <- 13
        ch <- 21
        //time.Sleep(time.Second)
    }

    close(ch)
    wg.Wait()
}
func main() {
    var wg sync.WaitGroup
    ch := make(chan struct{}, 3)
    for i := 0; i < 10; i++ {
        ch <- struct{}{}
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            log.Println(i)
            time.Sleep(time.Second)
            <-ch
        }(i)
    }
    wg.Wait()
}

https://studygolang.com/articles/17811?utm_source=joyk.com&utm_medium=referral&hmsr=joyk.com

你可能感兴趣的:(Golang WaitGroup结合Channel 控制并发数量)