Go Memory Model
The missing synchronization in the code snippet you provided allows the compiler to optimize the for loop into a no-op, leaving i unmodified.
When you add a synchronization event, such as a channel operation or a mutex lock, the compiler can no longer make this optimization, and the goroutine will correctly increment i, as you expect.
The above is the detailed content of Why does my Go for loop not increment the loop variable when running concurrently?. For more information, please follow other related articles on the PHP Chinese website!