c++visual-c++clangatomiccompare-and-swap

Cross-platform Support for 128-bit Atomic Operations in Clang (Compare-And-Swap or Equivalent)


We are currently evaluating 128-bit atomic operation support across platforms and compilers, and I wanted to confirm the level of support available in Clang specifically.

Our reference point is the Windows API function InterlockedCompareExchange128, which performs an atomic compare-and-swap on 128-bit values.

We’re trying to determine:

Is there an equivalent of this functionality in Clang that works across all major platforms (Windows, Linux, macOS, ARM64)?

If so, does Clang provide built-in or intrinsic support (e.g., __atomic_compare_exchange, __sync_val_compare_and_swap) for 128-bit atomics on types like __int128 ?
Are there any known limitations when using 128-bit atomic types in Clang?

Our current targets include:

We’d appreciate any insights, especially if someone has dealt with cross-platform abstractions for 128-bit atomic CAS.

Thanks in advance!


Solution

  • The answer below is relevant for platforms/compilers that support a 128 integer type. According to @PeterCordes comment below at the moment MSVC does not. But clang - which you mentioned as your main compiler ("Is there an equivalent of this functionality in Clang") does support it. As much as it is worth - gcc supports it as well.


    As suggested in comments above (1, 2), you can use std::atomic.

    Not only that is supported on your target platforms, it is a part of the stadard library and therefore likely to work on other platforms as well.

    The main compiler you mentioned (clang) also support 128 bit integer type: __int128.
    Therefore with it you can simply use std::atomic<__int128> (or the equivalent unsigned if needed).

    You mentioned you need a compare-exchange like function. std::atomic has 2 methods for that:
    compare_exchange_weak and compare_exchange_strong.

    The _weak version might fail spuriously, so if you want to make it simple you could probably just use the _strong version. But before that I advise you to review the Notes section in the cppreference page.