Search code examples
catomicc11

Difference between __atomic_load_n and __atomic_load


I'm trying to learn more about C11 atomics and don't see why I would use __atomic_load_n over __atomic_load. The documentation simply states that one is generic, but the usages look the same:

Built-in Function: type __atomic_load_n (type *ptr, int memorder) This built-in function implements an atomic load operation. It returns the contents of *ptr.

The valid memory order variants are __ATOMIC_RELAXED, __ATOMIC_SEQ_CST, __ATOMIC_ACQUIRE, and __ATOMIC_CONSUME.

Built-in Function: void __atomic_load (type *ptr, type *ret, int memorder) This is the generic version of an atomic load. It returns the contents of *ptr in *ret.

https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html


Solution

  • They function identically, and internal to GCC they're used based on convenience and clarity.

    If you have a pointer you want to atomically load data into, it makes sense to do:

    __atomic_load(__ptr, __dest, mem_order);
    

    If you have a value or you're trying to return from a function it makes sense to do:

    return __atomic_load_n(__ptr, mem_order)
    

    Clearly they're isomorphic to one another, and in application code you should use the standard functions provided by <stdatomic.h> not compiler builtins.