我有一个任务,如果选择工作,则执行三个功能。我想限制每个功能的Horoutines数量。例如,使每个人最多只能运行10个goroutines。

func main() {
    checkMethod1 := true
    checkMethod2 := false
    checkMethod3 := true

    list := []string{"info1", "info2", "info3", "info5"}

    for _, value := range list {
        value := value
        if checkMethod1 {
            go func() {
                //use value
                fmt.Println(value)
            }()
        }
        if checkMethod2 {
            go func() {
                //use value
                fmt.Println(value)
            }()
        }
        if checkMethod3 {
            go func() {
                //use value
                fmt.Println(value)
            }()
        }
    }
    //finish
    fmt.Println("All done")
}

我知道您可以将goroutines的数量限制在工人库中。但是,如果我将一个限制为10个goroutines的工人库,则该数字由3个任务划分,我需要每个功能具有10个goroutines。

我可以创建3个池,但这对我来说似乎不是一种可行的方式。

我想使用此库来创建工作池:https://github.com/sourcegraph/conc

分析解答

这是一种方法:为每个选项使用缓冲通道,因此您可以限制活动goroutines:

m1:=make(chan struct{},10)
m2:=make(chan struct{},10)
m3:=make(chan struct{},10)
wg:=sync.WaitGroup{}

for _, value := range list {
   value := value
   if checkMethod1 {
       m1<-struct{}{}
       wg.Add(1)
       go func() {
           defer func() { 
              <-m1 
              wg.Done()
           }()
           // do work
       }()
   }
   if checkMethod2 {
       m2<-struct{}{}
       wg.Add(1)
       go func() {
           defer func() { 
               <-m2 
               wg.Done()
           }()
           // do work
       }()
   }
   ...

  wg.Wait()
}