Sharing Variables in Go: Understanding the Difference Between Two Cases
In Go, goroutines are lightweight concurrent tasks that can share memory and communicate using channels. Variable sharing among goroutines requires careful handling to avoid data race issues.
Consider the following Go program:
<code class="go">package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) x := i go func() { defer wg.Done() fmt.Println(x) }() } wg.Wait() fmt.Println("Done") }</code>
When executed, this program prints the expected output:
4 0 1 3 2
In this case, each goroutine has its own copy of the variable x, which is initialized with the current value of i when the goroutine is created. This is because x is declared within the anonymous function, and its scope is limited to that function.
Now, consider a slight modification to the program:
<code class="go">package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func() { defer wg.Done() fmt.Println(i) }() } wg.Wait() fmt.Println("Done") }</code>
This time, the output becomes:
5 5 5 5 5
The explanation lies in the way the variable i is used in the goroutine. Since i is declared outside the anonymous function, it's shared among all goroutines. In this case, when each goroutine executes fmt.Println(i), it's printing the final value of i, which is 5.
To verify this, we can add printing of the memory addresses of x and i within the goroutines. The output shows that x has different addresses for each goroutine, while i has the same address for all goroutines:
0xc0420301e0 0xc0420301f8 0xc0420301e8 0xc0420301f0 0xc042030200 0xc042030208
In conclusion, the difference in variable sharing between the two cases arises from the scope of the variable declared in the anonymous function. When a variable is declared within the anonymous function, it's private to that goroutine. On the other hand, a variable declared outside the anonymous function is shared among all goroutines.
The above is the detailed content of Why does sharing variables in Go lead to different outputs depending on their scope within anonymous functions?. For more information, please follow other related articles on the PHP Chinese website!