在多个go例程中返回先前的Wait之前,WaitGroup被重用

在多个go例程中返回先前的Wait之前,WaitGroup被重用

问题描述:

I have a go program with multiple goroutines. I am experiencing this error and I can't figure out why. This is my code logic:

main.go

for {
   ...
   go funcFile2()
}

Where funcFile2 is defined in File2.go and is called multiple times in a sort of loop

File2.go

var wg sync.WaitGroup

func func1(){
    defer wg.Done()
    return
}
func func2(){
    defer wg.Done()
    return
}
func func3(){
    defer wg.Done()
    return
}

func funcFile2(){
wg.Add(3)
go func1()
go func2()
go func3()
wg.Wait()
}

GO Version: go1.12.7

How can I solve?

我有一个带有多个goroutine的go程序。 我遇到此错误,我不知道为什么。 这是我的代码逻辑: p>

main.go strong> p>

  for {
 ... 
  go funcFile2()
} 
  code>  pre> 
 
 

其中funcFile2在File2.go中定义,并在某种循环中多次调用 p>

File2.go strong> p>

  var wg sync.WaitGroup 
 
func func1(){
延迟wg.Done()
 返回
} 
func func2(){
延迟wg.Done()
返回
} 
func func3(){
延迟wg.Done()
返回
} 
 
func funcFile2(  ){
wg.Add(3)
go func1()
go func2()
go func3()
wg.Wait()
} 
  code>  pre> 
 
 

GO版本:go1.12.7 p>

我该如何解决? p> div>

If funcfile2() is called from multiple goroutines, then they are all sharing the same WaitGroup wg, which is valid. You get this error because in one of the goroutines wg.Wait() is called, and then in another goroutine wg.Add(3) is called, which is not valid. You cannot add more to a waitgroup once it starts waiting.

You have to have a separate waitgroup for each goroutine that calls funcfile2(). If this is in a for-loop, you can do something like:

for {
   wg:=sync.WaitGroup{}
   go funcfile2(&wg)
}

That way each goroutine calling funcfile2 will use its own waitgroup. Of course, funcfile2 has to pass the same waitgroup to the goroutines it creates.