Home >Backend Development >Golang >Why Can Go\'s Concurrent Execution Lead to Unexpected Variable Values?
The GoLang memory model document states that the following code can result in g printing 2 followed by 0:
var a, b int func f() { a = 1 b = 2 } func g() { print(b) print(a) } func main() { go f() g() }
This behavior arises from the asynchronous nature of Go routines. Before any function execution, variables a and b are initialized to their respective zero values (0). The f() function modifies these variables, and the g() function subsequently prints their values.
Within a goroutine, the language specification ensures that reads and writes occur in the order specified by the program. However, reordering of operations may occur without affecting the goroutine's behavior, which is the case here.
In the f() goroutine, the compiler can optimize by reordering the assignments to b and a. Since the goroutine does not use these variables after assignment, the reordering does not affect its behavior.
Synchronization between goroutines, on the other hand, requires consistency. At synchronization points, the compiler guarantees that all assignments have been completed, ensuring that both a and b have their assigned values by the time the g() goroutine reads them. This ensures correct printing of the modified values (2 and 1).
The above is the detailed content of Why Can Go\'s Concurrent Execution Lead to Unexpected Variable Values?. For more information, please follow other related articles on the PHP Chinese website!