Sign in

Go language concurrent with once question?

mstdmstd edited in Sun, 04 Dec 2022

Looking at the official document, there is a piece of code in the document

var a string
var done bool

func setup() {
    a = "hello, world"
    done = true

func doprint() {
    if !done {

func twoprint() {
    go doprint()
    go doprint()
This version can (incorrectly) print an empty string instead of "hello, world".

Why might this code produce the wrong result.

1 Replies
commented on Sun, 04 Dec 2022

When a goroutine sees done as true, it has no synchronization with other goroutines.

However, at this time, the "a" seen by the goroutine may still be "a".

When there is no synchronous operation, different goroutines may see different orders of instruction execution. It may even see "intermediate results" of instruction execution that should not appear.