Here is some strange idea. I don’t know exactly how you set up your data structure. But if possible, you can store two int values in long , then I think you can change them atomically.
For example, let's say you wrapped two values as follows:
class SwappablePair { long m_pair; public SwappablePair(int x, int y) { m_pair = ((long)x << 32) | (uint)y; }
Then it seems that you can add the following Swap method to cause the pair to be replaced “atomically” (in fact, I don’t know if it is fair to say that the following is atomic, it looks more like 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 very possible that I did it wrong, of course. And there may be a flaw in this idea. This is just an idea.
Dan Tao 04 Oct '10 at 18:16 2010-10-04 18:16
source share