开发者

Can Interlocked.Exchange exchange two byte[] arrays?

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 wit开发者_运维技巧h Interlocked.Exchange ? I see it works for int arrays in docs.

Thanks!


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


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.


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜