I think I slightly got the idea what exactly Volatile.Write
and Volatile.Read
do, but I've seen some examples where Volatile.Write
is used at the beginning of a method like in the CLR via C# book where Jeffrey shows how to implement a Simple Spin Lock using Interlocked
. Here's the code:
struct SimpleSpinLock {
private int _resourceInUse; // 0 = false, 1 = true
public void Enter() {
while (true) {
if (Interlocked.Exchange(ref _resourceInUse, 1) == 0) return;
}
}
public void Leave() {
Volatile.Write(ref _resourceInUse, 0); // Why is it here??
}
}
This is how the class is suppose to be used:
class SomeResource {
private SimpleSpinLock _s1 = new SimpleSpinLock();
public void AccessResource() {
_s1.Enter();
// Some code that only one thread at a time can get in..
_s1.Leave();
}
}
So as I know Volatile.Write
is used to guarantee that instructions which are above it will be executed exactly before the Volatile.Write
. But in the Leave
method there is only one instruction and what's the reason to use Volatile.Write
here? Probably I understand the things completely wrong, so I'd be grateful if someone could lead me to the right way.
Would not claim that I have enough brainpower to fully understand/explain this, but here are my 5 cents. First of all compiler can inline Leave
method call cause it consists of only one line, so actual write can be surrounded by other instructions. Secondary (and mainly, I suppose) the Volatile
class docs state next:
On a multiprocessor system, a volatile write operation ensures that a value written to a memory location is immediately visible to all processors.
So the goal of this Volatile.Write
call to make the change seen to other processor as soon as possible.
Also see answers to this question and read about volatile
keyword