Question

Does the c# memory model guarantee that a thread holding a lock is guaranteed to see all updates performed while any other thread previously held the same lock?

I have been reading the c# specification but cant seem to find the specifics on this.

Was it helpful?

Solution 2

Yes, subject to certain restrictions.For details, the section you are looking for is 3.10.

OTHER TIPS

Going for the intuitive explanation: if that guarantee wasn't provided then you couldn't implement a lock.

Going for the formal explanation: this is covered by the CLI spec (Ecma 335), chapter I.12.6.5:

Acquiring a lock (System.Threading.Monitor.Enter or entering a synchronized method) shall implicitly perform a volatile read operation, and releasing a lock (System.Threading.Monitor.Exit or leaving a synchronized method) shall implicitly perform a volatile write operation.

A volatile read has “acquire semantics” meaning that the read is guaranteed to occur prior to any references to memory that occur after the read instruction in the CIL instruction sequence. A volatile write has “release semantics” meaning that the write is guaranteed to happen after any memory references prior to the write instruction in the CIL instruction sequence.

Locking just pauses other threads that want the lock. This guarantees that only one thread performs the update to the share data.

When, the lock is realeased, another thread can then update the data and it would see the previous thread's updates.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top