Middle+
// numbers from 1 to 10 func main() { done := make(chan struct{}, 10) for i:=1; i<=10; i++{ go func(){ defer func() {done<-struct{}{}}() printNumber(n) }() } for i:=1; i<=10; i++{ <-done } } func printNumber(n int) { time.Sleep(time.Second) fmt.Println(n) }
sobes.tech AI
Answer from AI
The provided code has several errors:
-
The goroutine uses the variable
n, which is not defined. You need to passias a parameter to the anonymous function to avoid closure issues. -
The
donechannel is created with a buffer of 10, which is not critical, but it can be unbuffered.
Corrected version:
package main
import (
"fmt"
"time"
)
func main() {
done := make(chan struct{})
for i := 1; i <= 10; i++ {
go func(n int) {
defer func() { done <- struct{}{} }()
printNumber(n)
}(i)
}
for i := 1; i <= 10; i++ {
<-done
}
}
func printNumber(n int) {
time.Sleep(time.Second)
fmt.Println(n)
}
Explanation:
- Passing
ias a parameternin the goroutine captures the value for each iteration. - The
donechannel is used for synchronization — the main thread waits for all goroutines to finish. printNumberoutputs the number with a 1-second delay.
This way, the program correctly prints numbers from 1 to 10 (in any order, since goroutines run in parallel).