Always have x number of goroutines running at any time

前端 未结 7 1806
鱼传尺愫
鱼传尺愫 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:43

    Grzegorz Żur's answer is the most efficient way to do it, but for a newcomer it could be hard to implement without reading code, so here's a very simple implementation:

    type idProcessor func(id uint)
    
    func SpawnStuff(limit uint, proc idProcessor) chan<- uint {
        ch := make(chan uint)
        for i := uint(0); i < limit; i++ {
            go func() {
                for {
                    id, ok := <-ch
                    if !ok {
                        return
                    }
                    proc(id)
                }
            }()
        }
        return ch
    }
    
    func main() {
        runtime.GOMAXPROCS(4)
        var wg sync.WaitGroup //this is just for the demo, otherwise main will return
        fn := func(id uint) {
            fmt.Println(id)
            wg.Done()
        }
        wg.Add(1000)
        ch := SpawnStuff(10, fn)
        for i := uint(0); i < 1000; i++ {
            ch <- i
        }
        close(ch) //should do this to make all the goroutines exit gracefully
        wg.Wait()
    }
    

    playground

提交回复
热议问题