限制在循环中选择任务的goroutine数量

huangapple go评论75阅读模式
英文:

Limit number of goroutine picking task in loop

问题

我正在运行一个循环,循环次数为24次,每次调用一个下游函数。这个下游函数不能同时处理由生成的go协程提供的所有工作,我想限制只有特定数量(3或4个)的go协程被执行。

示例代码如下,如果有人能指导我正确的模式来实现这个目标,将会非常有帮助:

for i := 0; i < 24; i++ {
   go callSomeDownStream()
}
英文:

I am running a loop - 24 times which calls a downstream that is not able to handle all the work supplied concurrently by the go-routines spawned, I want to limit that such that only a specific number (3 or 4) of go-routine gets executed.
Sample code looks like below, if anyone can point me to the right pattern to fulfil this would be a great help

for i:=0; i&lt;24; i++ {
   go callSomeDownStream()
}

答案1

得分: 2

你可以使用空结构体的通道来控制并发工作协程的数量。

const MAX_CONCURRENT_JOBS = 3

func main() {
	waitChan := make(chan struct{}, MAX_CONCURRENT_JOBS)

	for i := 0; i < 24; i++ {
		waitChan <- struct{}{}
		go func() {
			callSomeDownStream()
			<-waitChan
		}()
	}
}

这段代码中,通过创建一个容量为MAX_CONCURRENT_JOBS的空结构体通道waitChan来控制并发工作的数量。在循环中,每次向waitChan通道发送一个空结构体,表示有一个工作协程开始执行。然后,使用匿名函数启动一个协程来调用callSomeDownStream()函数,并在协程结束时从waitChan通道接收一个空结构体,表示一个工作协程结束。通过控制waitChan通道的容量,可以限制并发执行的协程数量。

英文:

You can use the channel of empty structs to control the number of concurrent worker goroutines

const MAX_CONCURRENT_JOBS = 3

func main() {
	waitChan := make(chan struct{}, MAX_CONCURRENT_JOBS)

	for i:=0; i &lt; 24; i++ {
		waitChan &lt;- struct{}{}
		go func() {
			callSomeDownStream()
			&lt;-waitChan
		}()
	}
}

答案2

得分: 1

func callSomeDownStream(wg *sync.WaitGroup, queue chan struct{}) {
    defer func() {
        <-queue
        wg.Done()
    }()
    // 做一些操作
}

func main() {
    wg := sync.WaitGroup{}
    queue := make(chan struct{}, 3)
    for i := 0; i < 24; i++ {
        queue <- struct{}{}
        wg.Add(1)
        go callSomeDownStream(&wg, queue)
    }
    wg.Wait()
    close(queue)
}

以上是要翻译的代码。

英文:
func callSomeDownStream(wg *sync.WaitGroup, queue chan struct{}) {
    defer func() {
	    &lt;-queue
	    wg.Done()
    }()
    // do something
}

func main() {
    wg := sync.WaitGroup{}
    queue := make(chan struct{}, 3)
    for i := 0; i &lt; 24; i++ {
	    queue &lt;- struct{}{}
	    wg.Add(1)
	    go callSomeDownStream(&amp;wg, queue)
    }
    wg.Wait()
    close(queue)
}

huangapple
  • 本文由 发表于 2022年10月9日 16:03:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/74003057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定