Hello, please help me figure out the WaitGroup, I’m completely confused, the goroutine is executed once on the server and then crashes when you run the function again, displaying panic: sync: negative WaitGroup counter and the server crashes, I understand my function execution counter is 0 , but how to increase it, it does not react in any way, explain how to fix it, I have already tried adding WhiteGroup wherever possible, and creating a new one everywhere displays the same & {{} [0 0 0]} or & {{} [0 1 0]}
function itself
func Scan(cmdSc *pb.ScanCommandReq) []*models.Cmdrun {
wgAllScan := new(sync.WaitGroup)
var results []*models.Cmdrun
CheckFolder(cmdSc.TrgDst)
go cmdTicker()
ports := FPorts()
for _, port := range ports["segFir"] {
scanFileRes := fmt.Sprint(cmdSc.TrgDst+"/"+cmdSc.TrgDst, time.Now().UnixNano()) + "def"
wgAllScan.Add(1)
fileXMLCreate(scanFileRes)
go runScan(newScan, scanFileRes, port)
}
go func(wg *sync.WaitGroup) {
for res := range resultsCh {
fmt.Println(wgAllScan)
// I output the WhiteGroup at the first execution it turns out as it
// should be & {{} [1 8 0]} that is, wait for 8 goroutines to
// complete, and the next time I press execute and outputs & {{} [0 0 0]}
if res.StateProc == 0 {
host, err := ParseXMLResultFile(res.FileScan)
if err != nil {
log.Printf("Parsing file not done: %s", err)
}
results = append(results, host)
err = os.Remove(res.FileScan)
if err != nil {
log.Fatal("Can't delete file", res.FileScan, err)
}
}
wgAllScan.Done()
}
}(wgAllScan)
wgAllScan.Wait()
return results
}
go func(wg *sync.WaitGroup) {
for res := range resultsCh {
wgAllScan.Add(1)
fmt.Println(wgAllScan)
if res.StateProc == 0 {
host, err := ParseXMLResultFile(res.FileScan)
if err != nil {
log.Printf("Parsing file not done: %s", err)
}
results = append(results, host)
err = os.Remove(res.FileScan)
if err != nil {
log.Fatal("Can't delete file", res.FileScan, err)
}
}
then the goroutine works out as much as needed, but then my main function will stop waiting for the goroutine and finish its execution
if I add wgAllScan.Add (1) to both the first loop and the second, then the function runs many times without completing but the counter never completes and leaks again.
I don’t understand how to proceed
I tried to put this together in the playground to see the channel behavior, but I cannot because there are some variables that aren’t shown in your code above: https://play.golang.org/p/HjusoualI8y