首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

atomic_fetch_add_explicit

在头文件<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和添加arg到旧值的结果obj,并返回obj先前保存的值。操作是读取 - 修改 - 写入操作。第一个版本根据命令对内存进行访问memory_order_seq_cst,第二个版本根据内存访问内存访问order

这是为所有原子对象类型定义的通用函数A。该参数是指向易失性原子类型的指针,以接受非易失性和易失性(例如内存映射I/O)原子变量的地址。M或者是对应于非原子类型A,如果A是原子整数类型,或者ptrdiff_t如果A是原子指针类型。

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

参数

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

参考

  • C11标准(ISO/IEC 9899:2011):
    • 7.17.7.5 atomic_fetch和修改泛型函数(p: 284-285)

另请参阅

atomic_fetch_subatomic_fetch_sub_explicit (C11)

atomic subtraction (function)

| atomic_fetch_add,atomic_fetch_add_explicit的C ++文档 |

扫码关注腾讯云开发者

领取腾讯云代金券