Always have x number of goroutines running at any time

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

    Here I think something simple like this will work :

    package main
    
    import "fmt"
    
    const MAX = 20
    
    func main() {
        sem := make(chan int, MAX)
        for {
            sem <- 1 // will block if there is MAX ints in sem
            go func() {
                fmt.Println("hello again, world")
                <-sem // removes an int from sem, allowing another to proceed
            }()
        }
    }
    
    0 讨论(0)
提交回复
热议问题