__atomic_load_n 和 __atomic_load 之间的区别

Difference between __atomic_load_n and __atomic_load

我正在尝试了解有关 C11 原子的更多信息,但不明白为什么我会使用 __atomic_load_n 而不是 __atomic_load。文档只是说一个是通用的,但是用法看起来是一样的:

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

它们的功能相同,并且在 GCC 内部使用它们是为了方便和清晰。

如果你有一个指针,你想以原子方式加载数据,这样做是有意义的:

__atomic_load(__ptr, __dest, mem_order);

如果您有一个值或者您正试图从一个函数中 return 这样做是有意义的:

return __atomic_load_n(__ptr, mem_order)

很明显,它们彼此同构,在应用程序代码中,您应该使用 <stdatomic.h> 提供的标准函数,而不是编译器内置函数。