Variables a and b are allocated and initialized with zero values ββof their corresponding type (which is 0 in the case of int ), before any of the functions starts execution, in this line:
var a, b int
What can change is the assignment of new values ββto them in the function f() .
Quote from this page: It happens before :
Inside one goroutine, reading and writing should behave as if they were running in the order specified by the program. That is, compilers and processors can change the order of reading and writing performed in one rope only if reordering does not change the behavior inside this goroutine, as defined by the language specification. Due to this reordering, the execution order observed by one goruta may differ from the order perceived by another. For example, if one goroutine does a = 1; b = 2; a = 1; b = 2; , another may observe the updated value of b before the updated value of a .
Assignment a and b may not happen in the order in which you write them, if their reordering does not affect the same goroutine. The compiler can reorder them, for example, if the first change in the value of b more efficient (for example, since its address is already loaded into the register). If changing the assignment order (or may) cause a problem in the same goroutine, then, obviously, the compiler is not allowed to reorder. Since the goroutine of f() does nothing with variables a and b after assignment, the compiler can execute tasks in any order.
Since there is no synchronization between 2 goroutines in the above example, the compiler makes no effort to verify that reordering will cause any problems in another version of goroutine. It's not obligatory.
Buf, if you synchronize your goroutines, the compiler will make sure that there are no inconsistencies at the "synchronization point": you will have a guarantee that at that moment both assignments will be "completed"; therefore, if the "synchronization point" is before print() calls, then you will see the new values ββprinted: 2 and 1 .
source share