views:

17

answers:

2

In the following code:

a = Interlocked.Exchange(ref b, c);

I know b is set to c atomically. But is a also set to b in the same atomic operation? Or is this outside of the atomic operation.

What I need is to ensure both a and b are set in the same atomic operation.

c => b, b => a

This is in C#.Net.

A: 

Interlocked.Exchange Method (Int32, Int32) definition:

Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operation.

Code sample in MSDN article http://msdn.microsoft.com/en-us/library/d3fxt78a.aspx uses Interlocked.Exchange return code for thread-safe resource locking. So, the answer is yes, this is atomic operation.

Of course, if you run Interlocked.Exchange in different threads and assign return value to the same variable, result may be incorrect. But this is general thread safety rules - just use local variable.

Alex Farber
Thanks. The example in MSDN only shows examining the return value. I know the exchange is atomic. What I don't know is if setting the return value into a variable would also be part of the atomic operation.
IanC
I would minimally think a would have to be marked as volatile. This has nothing to do with atomicity, though.
IanC
No, return value assignment is not part of atomic operation, this can be checked on MSIL or native Assembly level. This is just not part of the function. This is safe if you use local stack-allocated variable to keep return value.
Alex Farber
+2  A: 

I assume you're considering code like this:

using System;
using System.Threading;

class Test
{
    static int x = 1;
    static int y = 2;

    static void Main()
    {
        x = Interlocked.Exchange(ref y, 5);
    }
}

In that case, no, the operation isn't atomic. In IL, there are two separate actions:

  • Calling the method
  • Copying the value from the notional stack to the field

It would be entirely possible for another thread to "see" y become 5 before the return value of Interlocked.Exchange was stored in x.

Personally, if I were looking at something where you need multiple field values to be changed atomically, I'd be considering locks instead of atomic lock-free operations.

Jon Skeet
Thanks @Jon. This is what I was afraid of.
IanC
IanC
@IanC: I don't know that there *is* a .NET equivalent, to be honest.
Jon Skeet