要点

  1. 带缓存的channel
  2. WaitGroup

示例

func main() {

    // goroutine同时运行数量
    ch := make(chan bool, 5)
    var synWait sync.WaitGroup

    // 执行总数量
    count := 10
    for i := 0; i < count; i++ {
        synWait.Add(1)
        ch <- true

        go func() {
            time.Sleep(time.Second)
            fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
            <-ch
            synWait.Done()
        }()

    }

    synWait.Wait()
}

打印的结果为

2020-04-30 11:31:31
2020-04-30 11:31:31
2020-04-30 11:31:31
2020-04-30 11:31:31
2020-04-30 11:31:31
2020-04-30 11:31:32
2020-04-30 11:31:32
2020-04-30 11:31:32
2020-04-30 11:31:32
2020-04-30 11:31:32

可见一秒执行了5次,正好为channel控制的同时goroutine数量

Last modification:September 22nd, 2020 at 09:29 am
If you think my article is useful to you, please feel free to appreciate