New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
i+=1
as a only code line in a for loop didn't work normally
#36012
Comments
This problem also happens on go version go1.13.4 linux/amd64. package main
import (
"fmt"
"time"
)
func main() {
var i, j int
noop := func() {}
onlyAdd := func() {
fmt.Println("onlyAdd runs")
for {
i += 1
}
}
notOnlyAdd := func() {
fmt.Println("notOnlyAdd runs")
for {
j += 1
noop()
}
}
go onlyAdd()
go notOnlyAdd()
for {
fmt.Println("i is", i, " and j is", j)
time.Sleep(time.Second)
}
} output:
|
Same issue on macos on go1.13.4 darwin/amd64.
|
You have a data race. You can see it if you do You should use https://golang.org/wiki/Questions for general questions about why your code doesn't work. |
if use
it looks like the race tool affected the code? |
I know there is a data race in the code, but a data race would not make the for loop not adding |
This is an infinite loop with no synchronization. No other thread is guaranteed to ever see the increment (because that would be a data race, and behavior under data races is undefined), so the compiler optimizes it away. |
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
yes
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
1. origin question
run following go script and get different output with and without the comment line
with the comment line I get
but strangely, without that comment line I get:
2. debug by checking assemble code
with and without the comment line I get different assemble code:
assemble code shown below include the anonymous function run by go routine only.
without that comment line:
with that comment line:
it seems like go complier ignore that
i+=1
when complie into assemble code, and make thati+=1
do nothing.command I use to generate assemble code:
What did you expect to see?
output of main.go is the same, with and without that comment line
What did you see instead?
different output
The text was updated successfully, but these errors were encountered: