Golang waitGroup issue

So I have a simple script that runs 11 times of calSauare function. However, I set wg.Add(10), so When I run script 1, it returns an error:

But, when I set time.Sleep(time.Second * 3) to time.Sleep(time.Second * )`. The program returns no error:
image

Why?

script 1:

package main

import (
	"fmt"
	"time"
	"runtime"
	"sync"
)

func calSauare(i int, wg *sync.WaitGroup) {
	time.Sleep(time.Second * 3)
	fmt.Println(i*i)
	wg.Done()
}

func main() {
	fmt.Println(runtime.NumCPU())

	var wg sync.WaitGroup

	wg.Add(10)


	start := time.Now()

	for i:=0; i<=10; i++ {
		go calSauare(i,&wg)
	}

	wg.Wait()
	duration := time.Since(start)

	fmt.Println("This program took " ,duration)
}

script 2:

package main

import (
	"fmt"
	"time"
	"runtime"
	"sync"
)

func calSauare(i int, wg *sync.WaitGroup) {
	time.Sleep(time.Second * 1)
	fmt.Println(i*i)
	wg.Done()
}

func main() {
	fmt.Println(runtime.NumCPU())

	var wg sync.WaitGroup

	wg.Add(10)


	start := time.Now()

	for i:=0; i<=10; i++ {
		go calSauare(i,&wg)
	}

	wg.Wait()
	duration := time.Since(start)

	fmt.Println("This program took " ,duration)
}

The negative wait group error is because you initialized the wait group to 10, and started 11 goroutines. By rights they should both crash. Wait group count must equal the number of routines you start.

You should either use wg.Add(11) or increment the wait group inside the loop which will ensure it is correct:

func main() {
	fmt.Println(runtime.NumCPU())

	var wg sync.WaitGroup

	start := time.Now()

	for i := 0; i <= 10; i++ {
		wg.Add(1)
		go calSauare(i, &wg)
	}

	wg.Wait()
	duration := time.Since(start)

	fmt.Println("This program took ", duration)
}

Hi @Alistair_KodeKloud

Thank you for your response. I am aware that the proper approach is to loop 10 times or use wg.Add(11) . However, I am curious why, even if the loop runs 11 times and wg.Add(10) is set, this script doesn’t return an error when I simply change time.Sleep(time.Second * 3) to time.Sleep(time.Second * 1) .

BR

Both versions crash on mine. I have a 12 core CPU.
This is just concurrent programming. If you get synchronization wrong, then results can be undefined.

1 Like