Executing a closure goroutine fails to achieve the expected result


func main() {
    var number int = 0
    go func() {
        for {
    for {

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?


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


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.