Jul 03

In the last post, we’ve talked about memory fences. Today we’re going to keep looking at this topic, but we’re turning our attention to coding, ie, we’re going to talk about the options we have to add fences to our classes. In .NET, things are relatively straightforward.

Whenever we use one of the interlocked methods we’ve met in the past, we’re adding a full fence to our code. Locking will also end up using full fences. As you can see,  you’re already using full fences in several places. The good news is that you can also be specific about them, ie, there’s a method you can call if you want to add a fence to your code in a specific place: I’m talking about the Thread.MemoryBarrier static method (btw, this method will also add a  full fence).

Volatile reads or writes generate fences too! In C#, you can use the volatile keyword to mark a field as volatile. Reading a volatile field is the “equivalent” of having an acquiring fence. Writing to a volatile field can be seen as “adding” a release fence. Now,it’s important to notice that you’ll always get these read and write behaviors whenever you use the volatile field. If you’re looking for more control (ex.: you’ll only interested in having an acquire fence for a read),then you should rely on the Thread.VolatileRead or Thread.VolatileWrite methods for ensuring proper the desired behavior.

And I guess that’s all there’s time for today. In the next post, we’ll keep looking at multithreading and see how we can use these features on a C# program. Keep tuned!

1 comment so far

  1. Ivan Kotev
    11:27 am - 7-6-2009

    One small addition. In their current implementation VolatileRead and VolatileWrite use full memory fence. The internal implementation(Of course that can be changed) is:

    public static int VolatileRead(ref int address)
    int num = address;
    return num;