13

Like many other people, I've always been confused by volatile reads/writes and fences. So now I'm trying to fully understand what these do.

So, a volatile read is supposed to (1) exhibit acquire-semantics and (2) guarantee that the value read is fresh, i.e., it is not a cached value. Let's focus on (2).

Now, I've read that, if you want to perform a volatile read, you should introduce an acquire fence (or a full fence) after the read, like this:

int local = shared;
Thread.MemoryBarrier();

How exactly does this prevent the read operation from using a previously cached value? According to the definition of a fence (no read/stores are allowed to be moved above/below the fence), I would insert the fence before the read, preventing the read from crossing the fence and being moved backwards in time (aka, being cached).

How does preventing the read from being moved forwards in time (or subsequent instructions from being moved backwards in time) guarantee a volatile (fresh) read? How does it help?


Similarly, I believe that a volatile write should introduce a fence after the write operation, preventing the processor from moving the write forward in time (aka, delaying the write). I believe this would make the processor flush the write to the main memory.

But to my surprise, the C# implementation introduces the fence before the write!

[MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
public static void VolatileWrite(ref int address, int value)
{
    MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
    address = value;
}

Update

According to this example, apparently taken from "C# 4 in a Nutshell", fence 2 , placed after a write is supposed to force the write to be flushed to main memory immediately, and fence 3, placed before a read, is supposed to guarantee a fresh read:

class Foo{
  int _answer;
  bool complete;
  void A(){
    _answer = 123;
    Thread.MemoryBarrier(); // Barrier 1
    _complete = true;
    Thread.MemoryBarrier(); // Barrier 2
  }
  void B(){
    Thread.MemoryBarrier(); // Barrier 3;
    if(_complete){
      Thread.MemoryBarrier(); // Barrier 4;
      Console.WriteLine(_answer);
    }
  }
}

The ideas in this book (and my own personal beliefs) seem to contradict the ideas behind C#'s VolatileRead and VolatileWrite implementations.

17
  • Where did you read that? Feb 8, 2014 at 23:46
  • @ThomasLevesque near the end of the first answer to this question : stackoverflow.com/questions/10589654/…
    – dcastro
    Feb 8, 2014 at 23:49
  • The purpose of the fence is not to prevent the read from being cached. It is to prevent later reads from moving backward. Feb 9, 2014 at 15:40
  • 1
    @RaymondChen So you are saying that some processors guarantee that a read performed right before an acquire-fence will be fresh/immediate? Do you have any source? I can't seem to find that anywhere.
    – dcastro
    Feb 9, 2014 at 17:47
  • 2
    You asked me in email to comment on this thread. My comment is: when users have questions like this I refer them to people like Raymond Chen or Joe Duffy. I personally don't need to know the answer because I've fortunately never needed to write code that depended on volatility for its correctness. I try hard to avoid multithreading in the first place. Feb 10, 2014 at 16:07

2 Answers 2

9

How exactly does this prevent the read operation from using a previously cached value?

It does no such thing. A volatile read does not guarantee that the latest value will be returned. In plain English all it really means is that the next read will return a newer value and nothing more.

How does preventing the read from being moved forwards in time (or subsequent instructions from being moved backwards in time) guarantee a volatile (fresh) read? How does it help?

Be careful with the terminology here. Volatile is not synonymous with fresh. As I already mentioned above its real usefulness lies in how two or more volatile reads are chained together. The next read in a sequence of volatile reads will absolutely return a newer value than the previous read of the same address. Lock-free code should be written with this premise in mind. That is, the code should be structured to work on the principal of dealing with a newer value and not the latest value. This is why most lock-free code spins in a loop until it can verify that the operation completely successfully.

The ideas in this book (and my own personal beliefs) seem to contradict the ideas behind C#'s VolatileRead and VolatileWrite implementations.

Not really. Remember volatile != fresh. Yes, if you want a "fresh" read then you need to place an acquire-fence before the read. But, that is not the same as doing a volatile read. What I am saying is that if the implementation of VolatileRead had the call to Thread.MemoryBarrier before the read instruction then it would not actually produce a volatile read. If would produce fresh a read though.

4
  • 5
    Good answer but not quite correct. Put simply, there is unfortunately NO way to guarantee a 'fresh' read on a machine running multiple cores. Memory barriers simply guarantee ordering. They cannot guarantee that a thread running on one core will read a value which has simultaneously been written on a different core. If this were feasible it would be possible to implement a synchronised boolean to control multithreaded entry to methods and completely do away with the need for locks.
    – 0b101010
    Jun 10, 2016 at 9:25
  • "Yes, if you want a "fresh" read then you need to place an acquire-fence before the read". Are you suggesting that if another thread wrote the variable and we read it by adding a fence before the read, we would get the latest value? I think that due to "special relativity (explained in the question's comments), it can't be guaranteed.
    – Petrakeas
    Jun 22, 2016 at 14:21
  • 1
    @Petrakeas: Yes, but be careful how you define "latest". By the time you use or make a decision based on the value it might not be the "latest" anymore. Also read the comment above. 0b101010 makes a good point about the subtleties of multi core systems. In short "fresh" or "latest" have to be interpreted very loosely here. Jun 26, 2016 at 2:28
  • The way I understand it is that "when" thread B sees the updated complete value it is guaranteed that it will see the updated answer value. However, it may not see it instantly. @0b101010 can you please comment on the following example that exercises "freshness"? stackoverflow.com/questions/38050681/…
    – Petrakeas
    Jun 27, 2016 at 9:48
6

The important thing to understand is that volatile does not only mean "cannot cache value", but also gives important visibility guarantees (to be exact, it's entirely possible to have a volatile write that only goes to cache; depends solely on the hardware and its used cache coherency protocols)

A volatile read gives acquire semantics, while a volatile write has release semantics. An acquire fence means that you cannot reorder reads or writes before the fence, while a release fence means you cannot move them after the fence. The linked answer in the comments explains that actually quite nicely.

Now the question is, if we don't have any memory barrier before the load how is it guaranteed that we'll see the newest value? The answer to that is: Because we also put memory barriers after each volatile write to guarantee that.

Doug Lea wrote a great summary on which barriers exist, what they do and where to put them for volatile reads/writes for the JMM as a help for compiler writers, but the text is also quite useful for other people. Volatile reads and writes give the same guarantees in both Java and the CLR so that's generally applicable.

Source - scroll down to the "Memory Barriers" section (I'd copy the interesting parts, but the formatting doesn't survive it..)

13
  • "it's entirely possible to have a volatile write that only goes to cache" .But the VolatileRead method does guarantee that the latest value will be seen, and VolatileWrite guarantees that the value will be immediately seen by all processors.
    – dcastro
    Feb 9, 2014 at 8:11
  • And all they do is add a fence after the read, or a fence before the write. I guess what I'm missing is: fences give you acquire-release semantics - but how do these semantics translate to fresh reads/committed writes?
    – dcastro
    Feb 9, 2014 at 8:12
  • @dcastro It guarantees that you see the newest value, it doesn't tell the implementation how to do that. Basically there are cache coherence protocols that don't invalidate cachelines but update them instead. Voila you now can see the most up-to-date value without having to write back to memory. It's a bit nitpicky, but it's a good idea to keep implementation details and what the spec says apart.
    – Voo
    Feb 9, 2014 at 12:38
  • 1
    @dcastro Correct me if I'm wrong but is it not physically impossible to guarantee a 'fresh' value regardless of how many barriers you have and where you put them. Imagine bar+read+bar on thread1 and bar+write+bar on thread2. Thread1 falls asleep after its first barrier, thread2 falls asleep after its write => bar+bar,write+read/read+write,bar+bar. What will you read? (Simplified because in reality the threads could execute simultaneously on different cores!) Volatile I believe guarantees that if you observe one of your threads, the values in the observed thread never arrive out of order.
    – AnorZaken
    Jan 7, 2015 at 16:22
  • 1
    [part2...] Volatile then basically says that a value must be manipulated in order, as opposed to out of order where a newer value may be overwritten by an older one. The barrier before the write: "Hey guys, I'm about to write to this variable, so if you have any pending writes please finish them before I do mine". (The barrier after the read though I believe isn't so much after the read as it is in between reading a value into the local variable and using the local variable.) (This is all based on my very limited understand and may potentially be wrong in many ways.)
    – AnorZaken
    Jan 7, 2015 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.