Skip to content

Instantly share code, notes, and snippets.

@nobishino
Last active December 2, 2022 12:08
Show Gist options
  • Save nobishino/8150346c30101e2ca409ed83c6c25add to your computer and use it in GitHub Desktop.
Save nobishino/8150346c30101e2ca409ed83c6c25add to your computer and use it in GitHub Desktop.
@nobishino
Copy link
Author

nobishino commented Dec 2, 2022

I have another question regarding the Go Memory Model.

(1) Can this program print "10", according to the Memory Model?
(2) If that is forbidden, which part of the Go Memory Model excludes such behavior?

https://go.dev/play/p/Fn5I0fjSiKj

package main

var x int = 0

func main() {
	go func() {
		x = 1
	}()
	print(x) // first read: 1
	print(x) // second read: 0
}

I draw a picture of the happens-before relation of this program.
https://gist.github.com/nobishino/8150346c30101e2ca409ed83c6c25add?permalink_comment_id=4388680#gistcomment-4388680

I think the answer to (1) is yes.
Both reads are concurrent with x = 1, so each read can observe both x = 0 and x = 1.
And there is no constraint between the results of the first read and the second read.
So the second read can observe x = 0 even if the first read observes x = 0.

But I'm not sure. Is this understanding correct?

スクリーンショット 2022-12-02 20 58 45

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment