* Joubin Houshyar <jhoush...@gmail.com> [160822 09:47]: > > > On Saturday, August 20, 2016 at 2:29:41 AM UTC-4, Yulrizka wrote: > > func process() *foo { > > var result *foo > > > > var wg sync.WaitGroup > > wg.Add(1) > > go func() { > > defer wg.Done() > > result = &foo{1} > > }() > > > > wg.Wait() > > > > return result > > } > > Your firend is correct that using a WaitGroup here does not in anyway > address concurrent access to the heap variable 'result'. > > This modified example should clear it up: > > func process() *foo { > var result *foo > var wg sync.WaitGroup > > wg.Add(1) > go func() { > defer wg.Done() > result = &foo{1} > }() > > // race condition on result > result = &foo{8} > > wg.Wait() > return result > } > > The issue here is the runtime scheduler and what execution order can occur > before the go routine execution 'process' has been stopped at wg.Wait. So > process can return a foo initiazed with either 1 or 8. > > I think the general Go developer intuiton here is that the go routine will > not run until the parent go routine has hit the wg.Wait (since there are no > explicit IO or blocking instructions between the go func() and wg.Wait. > However, using Go(1.7) the main loop will panic after as little as 1000 > loops.
In the original code given by the OP, there is only one assignment to result (in the goroutine), and only one read from result (in the return statement). The WaitGroup properly orders these statements, so there is no race condition. If the OP's friend was trying to say that there easily could be a race condition if the code was modified to access result in process() after the go stmt but before the Wait, he would be correct, or if the OP did not post the full code that his friend was talking about, there might also be a race condition in the code his friend saw. But the WaitGroup in the originally posted code does properly order the two accesses to result. ...Marvin -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.