```go func main() { wg := sync.WaitGroup{} for i := 0; i < 10; i++ { wg.Add(1) go func(wg sync.WaitGroup) { defer wg.Done() fmt.Println(i) }(wg) } wg.Wait() fmt.Println("some text") time.Sleep(1 * time.Minute) fmt.Println("some text2") } ```
sobes.tech AI
Answer from AI
This code has several errors related to the use of sync.WaitGroup and closures in goroutines.
-
Passing WaitGroup by value: In the goroutine function
func(wg sync.WaitGroup), the WaitGroup is passed by value, meaning it is copied. As a result, callingwg.Done()inside the goroutine decreases the counter of the copy, not the original object, which leads towg.Wait()in main never unlocking.The correct way is to pass a pointer to the WaitGroup:
func(wg *sync.WaitGroup)and callwg.Done(). -
Issue with variable i in closure: The variable
iis used inside the goroutine, but it is modified in the loop. Because of this, all goroutines may print the same value (usually 10).To fix this, pass
ias a parameter to the anonymous function:
for i := 0; i < 10; i++ {
wg.Add(1)
go func(wg *sync.WaitGroup, val int) {
defer wg.Done()
fmt.Println(val)
}(&wg, i)
}
- Final corrected code:
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(wg *sync.WaitGroup, val int) {
defer wg.Done()
fmt.Println(val)
}(&wg, i)
}
wg.Wait()
fmt.Println("some text")
time.Sleep(1 * time.Minute)
fmt.Println("some text2")
}
Thus, it is important to pass a pointer to the WaitGroup and to fix the loop variable's value for correct goroutine operation and synchronization.