?
This document uses PHP Chinese website manual Release
在頭文件<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
到舊值的結(jié)果obj
,并返回obj
先前保存的值。操作是讀取 - 修改 - 寫入操作。第一個(gè)版本根據(jù)命令對(duì)內(nèi)存進(jìn)行訪問memory_order_seq_cst
,第二個(gè)版本根據(jù)內(nèi)存訪問內(nèi)存訪問order
。
這是為所有原子對(duì)象類型定義的通用函數(shù)A
。該參數(shù)是指向易失性原子類型的指針,以接受非易失性和易失性(例如內(nèi)存映射I/O)原子變量的地址。M
或者是對(duì)應(yīng)于非原子類型A
,如果A
是原子整數(shù)類型,或者ptrdiff_t
如果A
是原子指針類型。
對(duì)于有符號(hào)整數(shù)類型,算術(shù)定義為使用二進(jìn)制補(bǔ)碼表示。沒有未定義的結(jié)果。對(duì)于指針類型,結(jié)果可能是一個(gè)未定義的地址,但操作沒有未定義的行為。
obj | - | 指向要修改的原子對(duì)象的指針 |
---|---|---|
arg | - | 要添加到存儲(chǔ)在原子對(duì)象中的值的值 |
order | - | 此操作的內(nèi)存同步排序:所有值都是允許的 |
之前保存的值是指向的原子對(duì)象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 10000The non-atomic counter is 9511
C11標(biāo)準(zhǔn)(ISO / IEC 9899:2011):
7.17.7.5 atomic_fetch和修改泛型函數(shù)(p:284-285)
atomic_fetch_subatomic_fetch_sub_explicit(C11) | 原子減法(函數(shù)) |
---|
| atomic_fetch_add,atomic_fetch_add_explicit |的C ++文檔