Home > Backend Development > Golang > Why Might Go\'s `go f(); g()` Print \'20\' Instead of \'21\'?

Why Might Go\'s `go f(); g()` Print \'20\' Instead of \'21\'?

DDD
Release: 2024-11-23 15:00:17
Original
772 people have browsed it

Why Might Go's `go f(); g()` Print

Incorrect Synchronization in Go Lang

The Go memory model document explains that the following code may result in g printing 2 and then 0:

var a, b int

func f() {
    a = 1
    b = 2
}

func g() {
    print(b)
    print(a)
}

func main() {
    go f()
    g()
}
Copy after login

Explanation:

  • Variables a and b are initialized to their zero values (0) before any function executes.
  • The Happens Before rule within the Go memory model permits compilers and processors to reorder operations within a single goroutine if the reordering does not affect its behavior.
  • In the f() function, the assignments to a and b may not occur in the specified order if the reordering does not make a difference in that goroutine.
  • Since the assignments have no impact in the f() function, the compiler may reorder them for efficiency reasons.
  • As there is no synchronization between the two goroutines (i.e., f() and g()) in the provided example, the compiler does not attempt to ensure consistency between them.
  • If, however, you introduce synchronization between the goroutines, the compiler will guarantee that at the synchronization point, both assignments will be "completed." This means that the correct values (2 and 1) will be printed in g().

The above is the detailed content of Why Might Go\'s `go f(); g()` Print \'20\' Instead of \'21\'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template