I already figured out how the code will behave the way I want, but I would like to understand why it behaves in a way that improves my understanding of Go concurrency.
I tested sync.WaitGroupto wait for some goroutines to complete, because I plan to make several downloads on Amazon S3 this way.
This was the source code:
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 result of: 6, 6, 6, 6, 6.
Instead of something like: 2, 4, 1, 5, 3.
Since the loop doesn't even go to 6, it made no sense to me. I later passed the variable ito an anonymous function as an argument, and then it behaved as I expected.
Why is this happening? I do not understand this.
source
share