1

What is the Posix equivalent to the Windows InterlockedExchange?

I have found the equivalent for InterlockedCompareExchange (i.e. __sync_val_compare_and_swap) but not simple exchange. I found this answer that gave a solution in assembly, but I need a cross platform/architecture C solution.

Nick Banks
  • 4,298
  • 5
  • 39
  • 65

1 Answers1

1

If you have access to C2011 stdatomic.h, then I believe atomic_exchange is what you are looking for.

I am not aware of any other standardized equivalent. In particular, the current version of POSIX does not mandate the presence of stdatomic.h (which is optional in C2011), and no version of POSIX has defined its own atomic operations, only higher-level thread synchronization operations (pthread_mutex_* for instakce).

zwol
  • 135,547
  • 38
  • 252
  • 361
  • Thanks @zwol. I will try it out. – Nick Banks Feb 09 '22 at 14:32
  • Seems everything blows up when I include that header: ``` /usr/lib/gcc/x86_64-linux-gnu/9/include/stdatomic.h:42:9: error: ‘_Atomic’ does not name a type 42 | typedef _Atomic signed char atomic_schar; | ^~~~~~~ ``` So perhaps I can't use it. – Nick Banks Feb 09 '22 at 14:36
  • @Nick Which compiler and compiler options? – n. m. could be an AI Feb 09 '22 at 14:48
  • @NickBanks Seconding n.m. -- that error message looks to me like, somehow, headers that are only meant to be used by GCC 9.x are being read by some other compiler. – zwol Feb 09 '22 at 14:50
  • I'm using GitHub CodeSpaces and letting cmake pick. So perhaps it's picking clang. – Nick Banks Feb 09 '22 at 14:58
  • I regret to say I can't help you with either codespaces or cmake. However, I can tell you that current versions of clang should have their own (different) copy of stdatomic.h, and that if I take the error message at face value it means the compiler you're using, whatever it is, doesn't support C2011 atomics at all. – zwol Feb 09 '22 at 15:01