This question already has an answer here:
package main
import "time"
import "fmt"
var i int = 0
func loopInc() {
for {
i++
}
}
func main() {
go loopInc()
<-time.After(1 * time.Millisecond)
fmt.Println(i)
}
This code would always print 0.
I dumped the executable file and found that the go my loopInc
function was compiled to a do-nothing loop. i++
doesn't exist in it.
Why?
</div>
It's all explained in the Go Memory Model.
In this example, there is not a happens before relationship between incrementing i
and and printing i
. Because there is not a happens before relationship, the main goroutine may or may not see the changes to i
.
The compiler is allowed to optimize away i++
because there's no guarantee that the changes to i
will be observed.