Executing a closure goroutine fails to achieve the expected result

Issue

func main() {
    var number int = 0
    go func() {
        for {
            number++
            //time.Sleep(time.Nanosecond)
        }
    }()
    for {
        fmt.Println(number)
        time.Sleep(time.Second)
    }
}

the printing of number is always 0, but after adding a time.Sleep(time.Nanosecond) statement in the for loop, the printing of the value becomes normal. Why?

Solution

You have a data race. Read the Go memory model:

https://golang.org/ref/mem

If there is no explicit synchronization using channels or locks between goroutines, then there is no happened-before relationship and no guarantee that one goroutine will see the effects of another one. If you’re using Go v1.13 or earlier, then busy-loops will not yield to other goroutines.

Answered By – Burak Serdar

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.