Unexpected Behavior of Go Concurrency with for Loops and Anonymous Functions
In Go concurrency, it's essential to understand the behavior of anonymous functions when launched as goroutines. This was demonstrated when attempting to use sync.WaitGroup to wait for multiple goroutines to complete Amazon S3 uploads.
The initial code used a for loop to launch goroutines, but the output surprisingly showed all goroutines printing the same value (6). This occurred because the goroutines were not scheduled until after the for loop was completed, so the value of i was 6 when they executed.
The code was modified to pass i as an argument to the anonymous function, resulting in the desired behavior. This is because passing i creates a new variable and captures the value at the time of invocation.
This behavior aligns with the Go FAQ, which states that when an anonymous function is launched as a goroutine, it captures the state of its surrounding variables at the time of creation. Passing i as an argument effectively copies the value at that moment.
Therefore, when using anonymous functions in goroutines, it's important to consider the closure behavior and use techniques like value passing to achieve the desired concurrency behavior.
The above is the detailed content of Why Do Go Goroutines Launched in a For Loop with Anonymous Functions All Print the Same Value?. For more information, please follow other related articles on the PHP Chinese website!