views:

953

answers:

8

What (if any) is the C# equivalent of the ASM command "XCHG".

With that command, which imo is a genuine exchange (unlike Interlocked.Exchange), I could simply atomically swap two ints, which is what I am really trying to do.

+18  A: 

Why isn't Interlocked.Exchange suitable for you?

If you require the exact memory locations to be swapped then you're using the wrong language and platform as .NET abstracts the memory management away so that you don't need to think about it.

If you must do something like this without Interlocked.Exchange, you could write some code marked as unsafe and do a traditional pointer-based swap as you might in C or C++, but you'd need to wrap it in a suitable synchronisation context so that it is an atomic operation.

Update
You don't need to resort to unsafe code to do a swap atomically. You can wrap the code in a synchronisation context to make it atomic.

lock (myLockObject)
{
  var x = Interlocked.Exchange(a, b);
  Interlocked.Exchange(b, x);
}

Update 2
If synchronisation is not an option (as indicated in the comments), then I believe you're out of luck. As you're chasing some unmeasured efficiency, you may want to concentrate elsewhere. If the swapping of two integer values is a huge performance hog, you're probably using the wrong platform.

Jeff Yates
It's not that I'm trying to get into memory management. I simply need to swap the values of two ints and do so atomically. Due to my design requirements, a lock is not an option.
IanC
@IanC: Why is a lock not appropriate? Perhaps if you're more forthcoming with ALL the details, you can get an answer. Trickling additional constraints as we go is not helpful.
Jeff Yates
@Jeff I'm trying to keep it simple as the swap is all I am interested in :). The application requires 1 thread to write millions of messages a second and another thread reads these relatively occasionally (1000/sec). A lock would just be too much unneeded overhead as it would have to lock/unlock with no contention millions of times a second. My current code works fine, but if I could swap the 2 ints, it would be more efficient.
IanC
@IanC: How do you know it would be more efficient? Seems to me that you're clutching at straws. Please post evidence.
Jeff Yates
@Jeff you are correct. .Net is not the best platform for this one requirement. But it's well suited for the rest of the project. For now, I will have to stick with my current code and see how that goes.
IanC
@Jeff - not sure why you think I'm clutching at straws. It's quite straightforward that locks take up time. Somehow I think we're missing each other somewhere.
IanC
@IanC: I said that because it appears you're optimizing without any evidence that your efforts will actually bear fruit. It was not in reference to locks, it was in reference to you requiring that the swap be atomic in the first place.
Jeff Yates
@Jeff: does `b = Interlocked.Exchange(ref a, b);` make the swap atomic, or does it hide the non-atomicness of the operation?
Matt Ellen
@Matt: The Interlocked.Exchange is atomic but the assignment to b as well is not.
Jeff Yates
@Jeff oh, I am 100% clear that the swap must be atomic. It's quite simple. Instead of swapping a with say 0, I want to swap it with b.
IanC
@IanC: I understand that you are clear that you want it, but you give no evidence as to why making this operation atomic will give you any benefit. It seems your chasing a perceived optimization rather than a real one.
Jeff Yates
Hm, I have problem with the lock here - it doesn't make the statement inside the code block atomic per-se - only atomicity for it would come from having that same lock elsewhere - access to the variables without it will break that atom just like that...
Daniel Mošmondor
@Daniel: You're right, you would have to guard the variables with that lock to be sure or use a critical section that does not rely on a specific lock object.
Jeff Yates
@Daniel: Of course, the latter isn't necessarily possible in .NET (as far as I am aware).
Jeff Yates
+3  A: 

Interlocked.Exchange is really the only thing you can do:

  var x = Interlocked.Exchange(a, b);
  Interlocked.Exchange(b, x);

You are correct that this will not be atomic, but with a local variable used you are guaranteed that the values are consistent as long as both lines execute. Your other options are unsafe code (for using pointers), using p/invoke to a native library, or redesigning so that it's no longer required.

Philip Rieck
It has to be atomic. Could you point me to a reference on how to do this with unsafe code?
IanC
Interlocked.Exchange is an atomic operation, however, 2 in a row is not without synchronisation. As indicated in the MSDN documentation - http://msdn.microsoft.com/en-us/library/system.threading.interlocked.exchange.aspx
Jeff Yates
@IanC unsafe c# will not make it any *more* atomic than that. If you really, really need XCHG, you'll have to write it yourself in c. Not sure transitioning will give you a huge performance edge over a slim lock, though. See something like this: http://www.codeproject.com/KB/cs/unmanage.aspx
Philip Rieck
@Jeff Yates Indeed 2 in a row is not atomic - that was my point here. He wants the actual *Swapping* of two values, not just a change in one value, and I'm saying that this is as close as you can get to it in pure c#
Philip Rieck
+1  A: 

Outside of Interlocked.Exchange, I'm assuming the XCHG command is probably an implementation of the XOR Swap, so you could write your own.

C syntax: (from wikipedia link)

 void xorSwap (int *x, int *y) {
     if (x != y) {
         *x ^= *y;
         *y ^= *x;
         *x ^= *y;
     }
 }

Edit this is not atomic, you would have to synchronize it yourself

KennyCason
That wouldn't be atomic as per the OP's requirments.
Jeff Yates
XCHG is an x86 CPU instruction and it's atomic in the sense that it cannot be interrupted by another instruction. The XOR swap isn't atomic without adding extra locking on the parameters first.
Rup
+1 for the XOR swap, although it is not an atomic routine.
Rob Vermeulen
@Rup ah, I wasn't aware of the requirement of being atomic.
KennyCason
+4  A: 

According to MSDN, Interlocked.Exchange is atomic.

If it is not suitable for you, you could implement XCHG in an unsafe section using C/C++.

Rob Vermeulen
That would seem to be the only solution. Thanks.
IanC
Without locks, I don't see how unsafe code will work either. Can't make it atomic without some sort of synchronisation.
Jeff Yates
@Jeff Yates You're right on the atomic part. What I wanted to say was that, in the unsafe section, you could use inline assembler to do the XCHG.
Rob Vermeulen
@Rob: Good point.
Jeff Yates
+31  A: 

This is the likely implementation for Interlocked.Exchange() in the CLR, copied from the SSCLI20 source:

FASTCALL_FUNC ExchangeUP,8
        _ASSERT_ALIGNED_4_X86 ecx
        mov     eax, [ecx]      ; attempted comparand
retry:
        cmpxchg [ecx], edx
        jne     retry1          ; predicted NOT taken
        retn
retry1:
        jmp     retry
FASTCALL_ENDFUNC ExchangeUP

It is superior to using XCHG because this code works without taking a bus lock. The odd looking jumping code is an optimization in case branch prediction data is not available. Needless to say perhaps, trying to do a better job than what has been mulled over for many years by very good software engineers with generous helpings from the chip manufacturers is a tall task.

Hans Passant
Indeed. Indubitably. Quite. +1
Jeff Yates
+1  A: 

Interlocked.Exchange is best way to swap two int values in a thread safe manner in c#.

Use this class , even you have multiprocessor computer and you never know in which processor your thread is going to run.

saurabh
A: 

I think I just found the best solution. It is:

Interlocked.Exchange() Method (ref T, T)

All the "new" variables can be set in a class (Of T) and swapped with the current variables. This enables an atomic snapshot to take place, while effectively swapping any number of variables.

IanC
Yes, the only issue I see with this approach is that suddenly you have to put your data in an immutable reference type, which may be overdoing it, depending on how often you're performing swaps.
Dan Tao
@Dan, I don't see any issue with that. This is swapping the pointer only, obviously. It won't affect writing to the object speed.
IanC
@IanC: I just mean that, if I understand you correctly, you would need to create a new object for every swap (like Interlocked.Exchange(pair, new Pair(pair.X, pair.Y))). Maybe that's fine; it just seemed a bit... heavy? Or perhaps I've misunderstood.
Dan Tao
@Dan I would only need to create 2 objects and simply keep swapping the 2 pointers to them. Once the swap is done and the data read, the object could be zero'd and would then be reads to be swapped. You see what I mean?
IanC
@IanC: I guess I assumed you were asking about an atomic swap because you're dealing with multiple threads. The problem with the idea you just described is that your "in-reserve" object could be modified by multiple threads concurrently, and then swapped having invalid values. You could possibly do this without continual object allocation using some sort of pool, but that might end up being overly complex for what should be a simple problem.
Dan Tao
@Dan the "in reserve" object would only be modified by one master controller thread. At this point, I'd have to get into a lengthy explanation that goes way beyond the original question's scope.
IanC
+7  A: 

Here's kind of a weird idea. I don't know exactly how you have your data structure set up. But if it's possible you could store your two int values in a long, then I think you could swap them atomically.

For example, let's say you wrapped your two values in the following manner:

class SwappablePair
{
    long m_pair;

    public SwappablePair(int x, int y)
    {
        m_pair = ((long)x << 32) | (uint)y;
    }

    /// <summary>
    /// Reads the values of X and Y atomically.
    /// </summary>
    public void GetValues(out int x, out int y)
    {
        long current = Interlocked.Read(ref m_pair);

        x = (int)(current >> 32);
        y = (int)(current & 0xffffffff);
    }

    /// <summary>
    /// Sets the values of X and Y atomically.
    /// </summary>
    public void SetValues(int x, int y)
    {
        // If you wanted, you could also take the return value here
        // and set two out int parameters to indicate what the previous
        // values were.
        Interlocked.Exchange(ref m_pair, ((long)x << 32) | (uint)y);
    }
}

Then it seems you could add the following Swap method to result in a swapped pair "atomically" (actually, I don't know if it's fair to really say that the following is atomic; it's more like it produces the same result as an atomic swap).

/// <summary>
/// Swaps the values of X and Y atomically.
/// </summary>
public void Swap()
{
    long orig, swapped;
    do
    {
        orig = Interlocked.Read(ref m_pair);
        swapped = orig << 32 | (uint)(orig >> 32);
    } while (Interlocked.CompareExchange(ref m_pair, swapped, orig) != orig);
}

It is highly possible I've implemented this incorrectly, of course. And there could be a flaw in this idea. It's just an idea.

Dan Tao
+1 for thinking out of the box.
Rob Vermeulen
Damn, why didn't I think of storing the 2 ints in a long! Good one!
IanC