Search code examples
goconcurrencymemory-barriers

Concurrent access to variable without lock


I was disturbed by a question,

should we add lock if only one thread write variable, and other thread just read variable?

so I write such code to test it

package main

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

var lock sync.RWMutex
var i = 0

func main() {
    runtime.GOMAXPROCS(2)
    go func() {
        for {
            fmt.Println("i am here", i)
            time.Sleep(time.Second)
        }
    }()
    for {
        i += 1
    }
}

The result is keep print i am here 0 even after second of time. I know a little about Memory barrier or cpu cache. but how could it be cache for such a long time? I think after a few time, it should read variable I already changed.

Can anyone who is master go or computer system could help answer, please?


Update: i know it is a wrong way to update variable like this, i want to know why it is undefined in cpu/memory view.


Solution

  • finally, i find this answers, i know with a data race you will get a undefined behave, but i want to know why it behave like that currently.

    this snap code is because complier just remove Add function, it never add.

    so we have lesson, if you write a undefined behave, you may got a moon - -

    complier will treat you code as rubbish, it does not have any value.