Skip to content
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

cmd/go: code/instruction with side effects is disappeared #40572

Closed
xiaopengli89 opened this issue Aug 4, 2020 · 1 comment
Closed

cmd/go: code/instruction with side effects is disappeared #40572

xiaopengli89 opened this issue Aug 4, 2020 · 1 comment

Comments

@xiaopengli89
Copy link

What version of Go are you using (go version)?

$ go version
go version go1.14.5 linux/amd64

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/tora/.cache/go-build"
GOENV="/home/tora/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/tora/go"
GOPRIVATE=""
GOPROXY="https://goproxy.cn,direct"
GOROOT="/usr/lib/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/home/tora/code/go/proj/foo/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build205500719=/tmp/go-build -gno-record-gcc-switches"

What did you do?

package main

import (
	"fmt"
	"runtime"
	"time"
)

var a int32 = 0

func main() {
	runtime.GOMAXPROCS(2)
	go func() {
		for {
			a = 5
			// If uncomment code below, everything is ok
			// runtime.Gosched()
		}
	}()
	go func() {
		for {
			fmt.Println("a:", a)
		}
	}()
	time.Sleep(200 * time.Second)
}

What did you expect to see?

Finally a: 5 should appear on the screen

What did you see instead?

Always a: 0 appears on the screen, and a = 5 instruction is disappeared. Is this the expected behavior?

0000000000491980 <main.main.func1>:
  491980:       90                      nop
  491981:       eb fd                   jmp    491980 <main.main.func1>
@randall77
Copy link
Contributor

Yes, this is allowed. There is no synchronization operation that would guarantee that the second goroutine would see the effects of the first one.

In the compiler, this happens because the memory state generated by the a=5 statement is never used, so it gets dead-code eliminated. That's why adding runtime.Gosched fixes it, because that call uses the aforementioned memory state.

@golang golang locked and limited conversation to collaborators Aug 4, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants