I'm checking this great post on java fences, in which fences are used for following example, to ensure that concurrent thread can always read latest value updated from other threads:
// CPU 0:
void shutDownWithFailure(void)
{
failure = 1; // must use SOB as this is owned by CPU 1
SFENCE // next instruction will execute after all SOBs are processed
shutdown = 1; // can execute immediately as it is owned be CPU 0
}
// CPU1:
void workLoop(void)
{
while (shutdown == 0) { ... }
LFENCE // next instruction will execute after all LOBs are processed
if (failure) { ...}
}
My question is, what's the advantage of using fences against volatile
.
Taking above example, if I make both failure
and shutdown
volatile, it should achieve the same?