Given the following:
package main
import (
"fmt"
"sync"
)
func main() {
n := 100
var wg sync.WaitGroup
wg.Add(n)
x := 0
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
x++
}()
}
wg.Wait()
fmt.Println(n, x)
}
I would expect x
to always reach 100
by the time it prints at the end, but it sometimes prints as low as 95
. What am I missing here?