开发者

Is the return value of Interlocked.Exchange also processed atomically?

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 outs开发者_如何学Cide 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜