This is a simple problem, but after reading Why do I need a memory barrier? I'm very confused about it.
In the example below, assume different threads are repeatedly calling Increment and Counter:
class Foo{
int _counter=0;
public int Counter
{
get { return _counter; }
}
public void Increment()
{
Interlocked.Increment(ref _counter);
}
}
Sorry if I'm misinterpreting Why do I need a memory barrier? but it seems like it's suggesting the class above might not be providing a freshness guarantee when reading the value of _counter. Could a thread that's repeatedly accessing the Counter property get forever stuck on an old value of Counter (because it is cached in the register)?
Is a memory barrier or a lock before return _counter;
necessary?