Jul 02

In the previous post, we’ve started looking at interlocked operations. As we’ve seen, interlocked operations are great at what they do but they won’t be usable in all scenarios (ie, don’t think that they’ll solve all your locks problems). To show how things might go awry when using interlocks, I’ll reuse a great example written by Raymond Chen a few years ago (I’m updating it to C#):

class Program
  private static Object _lock = new Object();
  public static Int64 InterlockedMultiply(
ref Int64 multiplicand, Int64 multiplier) { Int64 result = 0; lock (_lock) { var aux = multiplicand; Thread.Sleep(100);//oops!!! result = multiplicand = aux * multiplier; } return result; } static void Main(string[] args) { Int64 a = 5; new Thread(
() => InterlockedMultiply(
ref a, 5)).Start(); new Thread(() => {
Interlocked.Increment(ref a); }).Start(); Thread.Sleep(2000); Console.WriteLine(a); } }

The idea is to add a safe multiplier method. As we’ve seen in the previous post, interlocked increments are atomic. That means that they’re executed as a “single” operation by the processor. Since we didn’t had a method that performs the same operation for multiplication, we’ve decided to mimic that behavior by adding a new method which uses a lock to ensure proper multiplication.

If I asked you what Console.WriteLine(a) would print, what would you say? For now, forget those nasty Sleep invocations (they’re there to force the wrong behavior)… I’m guessing that you’d probably say that Console.WriteLine will only write 26 or 30. It will write 26 if InterlockedMultiply “beats” Increment or 30 if Increment is run before InterlockedMultiply. Ah, well,with those nasty sleep instructions,I’ve managed to get 25 here on my machine. Wtf? How? Why?

Well, what happened is logical…Interlocked.Increment will always update the value in a single atomic operation (this means it will load, update and then store the value in a “single” step). However, InterlockedMultiply only ensures that the code wrapped by the lock will only be executed by a thread at a time. Look at that method carefully…can you see a load followed by a store? Those two operations aren’t performed atomically like the one you get through the Interlocked.Increment method!

There is a solution to this problem, but it involves looping until you get a valid result. Take a look at the method updated to work correctly:

public static Int64 InterlockedMultiply(
ref Int64 multiplicand, Int64 multiplier) { Int64 result = 0; Int64 aux = 0; do { aux = multiplicand; result = aux * multiplier; } while ( Interlocked.CompareExchange(
ref multiplicand, result, aux) != aux); return result; }

As you can see, we’re using the Interlocked.CompareExchange method to ensure that multiplicand will only be updated if it hasn’t changed during the  execution of that loop. That happens because the Interlocked.CompareExchange method will always return the value that was stored in multiplicand at the time of the call (recall that CompareExchange always returns the original value of the 1st parameter passed to the method at the time of the call).

As you can see, interlocked operations don’t ensure proper serialization of your code. They only guarantee that the interlocked operation is done atomically. And I guess that’s all for now. Keep tuned for more on multithreading.

6 comments so far

  1. nomoreanxiety
    2:47 am - 11-27-2009

    Hi everyone

    Sorry to be off topic but I coudn”t resist sharing this, hoping it might help some of you.
    I am not really new to this forum but never bothered to write anything until now. I have reading around this and that forum to find some solution to my problems. I don”t want to bore you guys with my horror story but I would like to say a few words to encourage others.

    I use to get panic attacks since my childhood and now I am 26. I was some how living with it due to support from my father and friend. I am shy by nature and find it hard to mix with people and so I have few friends. But around 5 years ago, things turned to worst. I lost my parents in an accident. I then my life was turned upside down. I some how managed to get a boyfriend and I finally felt like coming back to life. I loved her and he too but I guess, I was making his life miserable and so he left, 6 months ago. Ok enough of my sad life.

    I actually never lost faith in myself. I was taking medication and I spent quite a lot of time on internet looking for some miracle information. I bought lot of books, CDs and what not. And then, I stumbled upon this course by Mr. Sal. It”s called Panic away. Just search for “panicaway dot com” and u will find it. I also tried the famous linden method but former seems to work better for me.

    And since then my life is slowly and slowly turning around.
    His approach is simple and yet effective. I started reading it around 4 months ago and the last attack that I got was 41 days ago. Earlier, it used to be like 1-2 times each week.I wish that I had found this course an year ago. Anyway. That”s it, I would say that you guys so give it a try and if this helps you then my effort of writing this looong post would be worthwhile.

    I am now looking forward to a life without fears. Wish me good luck.

  2. karrydido
    8:44 pm - 11-28-2009

    I just accidentally found this movie web site haha.

    This web site is just awesome! every streaming video is free and they put at least 5 different source for each TV episode then we can still watch even though one video is gone. I just watched 2012 and New Moon full streaming video~ high quality video, I love creamytv. They also have Asian media like korean, japanese, chinese like that wow! recommended. thumb 5 out of 5!

  3. Margaretnomr
    2:42 am - 12-10-2009

    Hello everybody

    I am a newbie colleague to this plaace. I look forward to a sober interaction with you all.

    cya all later

  4. amanda.hambright
    5:50 pm - 1-16-2010


    Just signed up on the forum

    I already like it here

  5. elena.walker
    12:57 am - 1-21-2010


    just got my account approved on the forum

    I already like it here

  6. elenahambright
    12:38 pm - 1-22-2010


    Just signed up on the forum

    hope to stay long here