2

I want to swap two byte arrays atomically, without the need for a lock. i.e. I don't want to do

    byte[] src;
    byte[] dest;
    lock(synchLock)
    {

       dest = src;
    }

Is this possible with Interlocked.Exchange ? I see it works for int arrays in docs.

Thanks!

Bala R
  • 107,317
  • 23
  • 199
  • 210
Jacko
  • 12,665
  • 18
  • 75
  • 126
  • 1
    You don't need Interlocked either, the CLR promises that reference updates are atomic. That however does *not* make it thread-safe. – Hans Passant May 07 '11 at 01:16

3 Answers3

3

Swap array references or swap their elements? References - yes, elements - no. There's no atomic command that works with arrays.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
1

Yes, Interlocked.Exchange supports all reference types and a few selected value types (Int32/64/Ptr, Single, Double).

ChrisWue
  • 18,612
  • 4
  • 58
  • 83
1

It's not clear what you're asking, but InterlockedExchange atomically does the following:

  1. reads the pre-existing value of the variable
  2. writes the variable

Note that only one variable is involved in the operation, along with two temporaries (the value being written, and the prior value returned). Whereas "swap" usually means writing two variables, such that each has the value which pre-existed in the other. That would be:

byte[] src;
byte[] dest;
lock(synchLock)
{
   var temp = dest;
   dest = src;
   src = temp;
}

InterlockedExchange cannot be used to implement lock-less swap with atomic effect on both variables.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720