atomic_fetch_add

本文介绍了C语言原子操作库中的atomic_fetch_add和atomic_fetch_add_explicit函数。这两个函数以加法结果原子地替换指针所指的值,并返回旧值。说明了参数、返回值,还给出示例展示原子操作与非原子操作的差异,体现原子操作在多线程中的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值