How Goroutines in Golang Share Variables
When learning Golang's concurrency features, an interesting question arises: how do goroutines share variables? A simple example illustrates the nuanced behavior.
Example 1
Consider the following code:
<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>
Output:
<code class="text">4 0 1 3 2</code>
Each goroutine correctly prints the intended value.
Example 2
Now, let's modify the code slightly:
<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>
Output:
<code class="text">5 5 5 5 5</code>
Explanation
The difference between these examples lies in how the variable x is captured by the goroutine. In Example 1, a new local variable x is created within each goroutine, allowing them to access the correct value.
In Example 2, however, the goroutine captures the variable i, which is a loop variable. As the loop iterates, i is updated, causing all goroutines to reference the same value at runtime.
This difference highlights the importance of variable scoping in Go concurrency. To avoid race conditions and unpredictable behavior, it's essential to capture the intended value in a new local variable.
The above is the detailed content of How Do Goroutines in Golang Share Variables?. For more information, please follow other related articles on the PHP Chinese website!