Monday 15 August 2011

go - Why is there a race condition in this program? -


I am looking at the Golg book, and I do not quite understand what is the problem in this program: / P>

  func main () {var wg sync.weaitgroup wg.Add (5) i: for = 0; I & lt; 5; I ++ {go func () {fmt.Println (i) // You are not looking for 'i' Wg.Done ()} ()} wg.Wait ()}   

It prints 5, 5, 5, 5, 5 when I expect print 0, 1, 2, 3, 4 (not necessarily In this order).

The way I see it, when Gourdin is made inside the loop, its value is known i (for example, someone can log a Printline (i) at the beginning of the loop and see the expected value). So I hope Gortine is expected to capture the value of i , when it is made and used later.

Obviously this is happening, but why?

Your task references i to external reference if you type I , the value of whatever you get i is now the price of i To use, provide an argument:

  func main () {var wg sync.WaitGroup wg. Add (5) for I: = 0; I & lt; 5; I ++ {go func (i int) {fmt.Println (i) wg.Done ()} (i)} wg.Wait ()}   



No comments:

Post a Comment