atomic

    xiaoxiao2023-10-27  161

    https://zh.cppreference.com/w/c/atomic/atomic_fetch_add atomic_fetch_add, atomic_fetch_add_explicit

    C

    原子操作库

    定义于头文件 <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 起)

    以 arg 和 *obj 的旧值的加法结果原子地替换 obj 所指向的值,并返回 *obj 先前保有的值。此操作是读修改写操作。第一版本按照 memory_order_seq_cst 排序内存访问,第二版本按照 order 排序内存访问。

    这是为所有原子对象类型 A 定义的泛型函数。该参数为指向 volatile 原子类型的指针,以接受非 volatile 和 volatile (例如内存映射 I/O )原子对象。若 A 为原子整数类型,则 M 是与 A 对应的非原子类型;若 A 为原子指针类型,则 M 为 ptrdiff_t 。

    对于有符号整数类型,定义算术为使用补码表示。无未定义结果。对于指针类型,结果可能是未定义地址,但运算不会另有未定义行为。 参数 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); // 原子的 ++cnt; // 未定义行为,实际上会失去一些更新 } 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

    引用

    C11 standard (ISO/IEC 9899:2011): 7.17.7.5 The atomic_fetch and modify generic functions (p: 284-285)
    最新回复(0)