Jurudocs
Jurudocs

Reputation: 9165

Having negative waitGroup counter but why

I'm trying to understand go routines and played around with some code. This one really makes me wonder. It's printing two or more values and then is erroring with

panic: sync: negative WaitGroup counter

func processTheInt(i int, wg sync.WaitGroup){
    fmt.Println(i)
    wg.Done()

}


func main(){
    var waitGroup sync.WaitGroup

    for {
        theInt := rand.Intn(100)
        waitGroup.Add(1)
        go processTheInt(theInt, waitGroup)
    }

}

Can someone explain why this is happening? Before executing the go func processTheInt I'm increasing the counter. The function executes and decreasing it after printing. Is it because the printing takes longer than kicking off the function?

Upvotes: 0

Views: 539

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

You should pass a pointer to waitGroup variable

func processTheInt(i int, wg *sync.WaitGroup){
    fmt.Println(i)
    wg.Done()

}

func main(){
    var waitGroup sync.WaitGroup

    for {
        theInt := rand.Intn(100)
        waitGroup.Add(1)
        go processTheInt(theInt, &waitGroup)
    }

}

Otherwise it will copy the struct on every for iteration.

Read this to know the difference

Upvotes: 6

Related Questions