命名空间
变体
操作

atomic_fetch_add, atomic_fetch_add_explicit

来自 cppreference.cn
< c‎ | atomic
定义于头文件 <stdatomic.h>
C atomic_fetch_add( volatile A* obj, M arg );
(1) (自 C11 起)
C atomic_fetch_add_explicit( volatile A* obj, M arg, memory_order order );
(2) (自 C11 起)

原子地将 obj 指向的值替换为 argobj 旧值的加法结果,并返回 obj 先前持有的值。此操作是读-修改-写操作。第一个版本根据 memory_order_seq_cst 对内存访问进行排序,第二个版本根据 order 对内存访问进行排序。

这是一个为所有 原子对象类型 A 定义的泛型函数。参数是指向 volatile 原子类型的指针,以接受非 volatile 和 volatile (例如,内存映射 I/O)原子对象的地址,并且当将此操作应用于 volatile 原子对象时,volatile 语义得以保留。如果 A 是原子整数类型,则 M 是对应于 A 的非原子类型;如果 A 是原子指针类型,则 Mptrdiff_t

泛型函数的名称是宏还是使用外部链接声明的标识符,这是未指定的。如果为了访问实际函数而抑制宏定义(例如,像 (atomic_fetch_add)(...) 这样加括号),或者程序定义了具有泛型函数名称的外部标识符,则行为是未定义的。

对于有符号整数类型,算术运算定义为使用二进制补码表示。没有未定义的结果。对于指针类型,结果可能是未定义的地址,但操作在其他方面没有未定义的行为。

目录

[编辑] 参数

obj - 指向要修改的原子对象的指针
arg - 要添加到原子对象中存储的值的值
order - 此操作的内存同步顺序:允许所有值

[编辑] 返回值

obj 指向的原子对象先前持有的值。

[编辑] 示例

#include <stdio.h>
#include <threads.h>
#include <stdatomic.h>
 
atomic_int acnt;
int cnt;
 
int f(void* thr_data)
{
    for(int n = 0; n < 1000; ++n) {
        atomic_fetch_add_explicit(&acnt, 1, memory_order_relaxed); // atomic
        ++cnt; // undefined behavior, in practice some updates missed
    }
    return 0;
}
 
int main(void)
{
    thrd_t thr[10];
    for(int n = 0; n < 10; ++n)
        thrd_create(&thr[n], f, NULL);
    for(int n = 0; n < 10; ++n)
        thrd_join(thr[n], NULL);
 
    printf("The atomic counter is %u\n", acnt);
    printf("The non-atomic counter is %u\n", cnt);
}

可能的输出

The atomic counter is 10000
The non-atomic counter is 9511

[编辑] 参考文献

  • C17 标准 (ISO/IEC 9899:2018)
  • 7.17.7.5 原子获取和修改泛型函数 (p: 208)
  • C11 标准 (ISO/IEC 9899:2011)
  • 7.17.7.5 原子获取和修改泛型函数 (p: 284-285)

[编辑] 参见

原子减法
(函数) [编辑]
C++ 文档 关于 atomic_fetch_add, atomic_fetch_add_explicit