Senior
```go func main() { wg := sync.WaitGroup{} wg.Add(8) for i := 0; i < 10; i++ { go func(wg *sync.WaitGroup, i int) { defer wg.Done() fmt.Println(i) }(&wg,i) } wg.Wait() fmt.Println("some text") time.Sleep(1 * time.Minute) fmt.Println("some text2") } ```
sobes.tech AI
Answer from AI
The provided code contains several errors and potential issues:
- Typo in the function parameter:
sync.WaitGropinstead ofsync.WaitGroup. - In the loop
for i := 0; i < 10; i++,wg.Add(8)is called, but 10 goroutines are launched — this will lead to a deadlock becausewg.Done()will be called 10 times, but the wait is only for 8. - Passing the variable
iinto the closure is correct, asiis passed as a parameter, preventing the classic closure mistake in loops.
Corrected example:
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
wg.Add(10) // The number of goroutines should match the Add
for i := 0; i < 10; i++ {
go func(wg *sync.WaitGroup, i int) {
defer wg.Done()
fmt.Println(i)
}(&wg, i)
}
wg.Wait()
fmt.Println("some text")
time.Sleep(1 * time.Minute)
fmt.Println("some text2")
}
Thus, the code correctly creates 10 goroutines, each printing its value of i, then the main thread waits for all goroutines to finish, prints "some text", waits a minute, and then prints "some text2".