1

Does a lock force variables to be written directly to memory instead of beëing cached like volatile does? in this question Orion Edwards states that using locks is better than using volatile, but if a public variable is accessed from within a lock, and always from that lock, does this mean that it is never cached outside of this lock statement?

private readonly object locker = new object();
private bool? _Var = null;

public bool? Var
{
    get 
    {
        lock (locker)
        {
            //possibly get the variable _Var in cache memory somewhere
            return this._Var;
            //force _Var back to memory
        }
    }
    set 
    {
        lock (locker)
        {
            //possibly get the variable _Var in cache memory somewhere
            this._Var = value;
            //force _Var back to memory
        }
    }
}
Community
  • 1
  • 1
Jeffnl
  • 261
  • 1
  • 4
  • 21

1 Answers1

1

A lock introduces an acquire-fence before its first instruction, and a release-fence after its last instruction.

The acquire-fence prevents instructions within the lock from being moved backwards in time and above the lock (i.e., "cached"). (Also, notice how it doesn't prevent instructions above the lock to be moved inside the lock).

This is what the specification guarantees. The mechanism used to achieve this (e.g., preventing the processor from using a register and writing/reading directly to/from memory, cache-invalidation, etc) isn't relevant.

dcastro
  • 66,540
  • 21
  • 145
  • 155
  • ok so if i'm correct the lock does protect the _Var variable as i described in the code? it is safe to use the lock in this example? – Jeffnl Jun 19 '14 at 11:50