I have already found out a way for the code to behave as I want, but I would like to understand why it behaves like this so that my understanding of Go concurrency improves.
I was testing out sync.WaitGroup
to wait for some goroutines to finish because I plan on doing multiple uploads to Amazon S3 in this way.
This was the code I had originally:
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go func() {
fmt.Println(i)
time.Sleep(time.Second * 1)
wg.Done()
}()
}
wg.Wait()
}
I was surprised to see that the output was: 6, 6, 6, 6, 6
.
Instead of something like: 2, 4, 1, 5, 3
.
Since the loop does not even go to 6, this made no sense to me.
I later passed the i
variable to the anonymous function as argument
and then it behaved as I expected.
Why does this happen? I don't understand it.