Sobes.tech
Senior

If you fix the bug with wg (pass a pointer) — what will we see on the screen when the program runs?

sobes.tech AI

Answer from AI

If you fix the bug with sync.WaitGroup by passing a pointer to wg instead of a copy, the program will correctly wait for all goroutines to finish before exiting.

Without passing a pointer, each goroutine works with a copy of the WaitGroup, and calls to Done() do not decrease the counter in the original wg. As a result, main may finish before the goroutines.

After fixing, the output on the screen will show the expected output of all goroutines, for example:

var wg sync.WaitGroup
wg.Add(2)

go func(wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Println("Goroutine 1 finished")
}(&wg)

go func(wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Println("Goroutine 2 finished")
}(&wg)

wg.Wait()
fmt.Println("All goroutines finished")

The output will be:

Goroutine 1 finished
Goroutine 2 finished
All goroutines finished

This means that main waited for all goroutines to finish.

If you fix the bug with wg (pass a pointer) — what… - sobes.tech