var wg sync.WaitGroup
var v int32 = 0
for i = 0; i < 100; i++{
go func(){
wg.Add(1) // wrong place
atomic.AddInt32(&v,1)
wg.Done()
}
}
wg.Wait()
fmt.Println(v)
Here is a piece of code I see from this video https://subscription.packtpub.com/video/application_development/9781788994880/97598/97608/goroutines
but the v
is always less than 100
, I think the reason could be the wg.Wait()
will over earlier than expectation because we put wg.Add(1)
inside the anonymous function and in the same goroutine wg.Done()
will be called immediately, thus main goroutine resume execution from blocked state.
But if we put the wg.Add(1)
into the for loop, v will always be 100
.
var wg sync.WaitGroup
var v int32 = 0
for i = 0; i < 100; i++{
wg.Add(1)
go func(){
atomic.AddInt32(&v,1)
wg.Done()
}
}
wg.Wait()
fmt.Println(v)
My question is why we can guarantee that main goroutine will always block here such that v will equal to 100 finally. Is that possible if before the for loop add one task to wg
, and main goroutine resume execution here since there is no task at that moment.