美文网首页
Golang WaitGroup结合Channel 控制并发数量

Golang WaitGroup结合Channel 控制并发数量

作者: zzz1t1 | 来源:发表于2022-01-27 16:40 被阅读0次
    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 控制并发数量

          本文链接:https://www.haomeiwen.com/subject/hryahrtx.html