How can I atomically swap two pointers on Windows?

Well, I ask the same thing as this remote question , but I ask it more directly.

I have two pointer variables in two instances of the same class. I would like to change the contents of these variables (not that they are POINT, but the variables themselves) atomically.

I would like to avoid locks, if at all possible.

How to do it?

EDIT: Answers to three calls to "InterlockedExchangePointer", please read the MSDN docs first . InterlockedExchangePointer swaps the value of a pointer-pointer with a value in a register . It by itself does not exchange two pointers in memory cells.

+6
c ++ windows
source share
3 answers

I am going to go on a limb and say that you need a lock, and that to solve this problem there is no solution protected from blocking.

You will need to read from two addresses and write to both addresses everything is atomic. As far as I know, X86 can only atomically exchange data from one memory address and register. I do not think it is possible to exchange the contents of two memory addresses.

If you can set limits on where the pointers are, you can do it. For example, if you can guarantee that pointers are contiguous in memory, you can use 64- or 128-bit comparison / exchange in a loop.

There may be solutions for other simple cases, but I donโ€™t think you will find a solution without blocking for the general case.

+13
source share

You are looking for an atomic, blocked version of swap .

As far as I know, there is no way to do this using only the Windows API primitives and without explicit blocking. Various Interlocked functions recommended by others will not work, because only one of the passed parameters is changed. You want to change both of them.

I could also indicate that Interlocked functions are only related to each other. If you have another piece of code that updates one of these pointers but doesn't use Interlocked , your code will no longer be safe. I am sure that you have realized this, but thought that I would say this.

As far as I know, you will need to use a library or write your own code to handle this.

+2
source share

Check the x86 instructions of the x86 processor if they do what you want, then you can wrap them in a built-in build function. All processor single instructions are guaranteed to be atomic.

-2
source share

All Articles