2

I found the InterlockedExchange function which allows me to exchange two signed 32-bit variables (LONG).

But, what is the correct way to atomically exchange two unsigned 32-bit variables (ULONG) under Windows?

I do not see an obvious way to do that using the functions provided by Microsoft.

(Considering that Microsoft also tells me that the result of converting unsigned integers to signed integers is implementation-defined in some cases.)

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70

2 Answers2

2

Simply use a type-cast:

ULONG value1, value2;
InterlockedExchange((LPLONG)&value2, (LONG)value1);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • As I said (see link above), the `(LONG)` cast is implementation-defined for results which cannot be represented. So how do you know what happens, if `value1` is e.g. equal to `4000000000u` which does not fit into a `LONG`? – heckenpenner_rot Mar 26 '14 at 19:13
  • If you hadn´t ignored the other answer here, 3 minutes before, you would know why you did get that wrong...it´s true, even if i have not that much rep – deviantfan Mar 26 '14 at 19:19
  • @user3465629 The implementation-defined behavior is documented: [LONG to ULONG preserves the bit pattern](http://msdn.microsoft.com/en-us/library/xbfs6fd4(v=vs.110).aspx). – Raymond Chen Mar 26 '14 at 19:21
  • 1
    The alternative is to force the bit pattern to be preserved manually, instead of relying on the compiler to do it: `InterlockedExchange((LPLONG)&value2, *((LPLONG)&value1));` – Remy Lebeau Mar 26 '14 at 19:25
  • @Raymond Chen. That's the part of information I was missing. Thanks a lot! I would add that especially for the *other* conversion, from `ULONG` to `LONG`, the bit pattern is also preserved. – heckenpenner_rot Mar 26 '14 at 19:33
0

In your link, casting a unigned something to types of different sizes
(and/or floting point stuff) is explained.
Casting only between signed and unigned of the same type
should be possible without any problems.

deviantfan
  • 11,268
  • 3
  • 32
  • 49