How do I atomically swap 2 ints in C#?

后端 未结 8 731
执念已碎
执念已碎 2020-11-29 06:50

What (if any) is the C# equivalent of the x86 asm xchg instruction?

With that command, which imo is a genuine exchange (unlike Interlocked.Exchange), I

相关标签:
8条回答
  • 2020-11-29 07:18

    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.

    0 讨论(0)
  • 2020-11-29 07:23

    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.

    0 讨论(0)
提交回复
热议问题