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.