Always have x number of goroutines running at any time

前端 未结 7 1807
鱼传尺愫
鱼传尺愫 2020-12-13 00:10

I see lots of tutorials and examples on how to make Go wait for x number of goroutines to finish, but what I\'m trying to do is have ensure there are always x number running

7条回答
  •  生来不讨喜
    2020-12-13 00:51

    You may find Go Concurrency Patterns article interesting, especially Bounded parallelism section, it explains the exact pattern you need.

    You can use channel of empty structs as a limiting guard to control number of concurrent worker goroutines:

    package main
    
    import "fmt"
    
    func main() {
        maxGoroutines := 10
        guard := make(chan struct{}, maxGoroutines)
    
        for i := 0; i < 30; i++ {
            guard <- struct{}{} // would block if guard channel is already filled
            go func(n int) {
                worker(n)
                <-guard
            }(i)
        }
    }
    
    func worker(i int) { fmt.Println("doing work on", i) }
    

提交回复
热议问题