Cpp-standard-library-cpp-fetch-add
提供:Dev Guides
C ++アトミックライブラリ-フェッチアド
説明
アトミックオブジェクトに格納されている値に引数を自動的にアトミックに追加し、以前に保持されていた値を取得します。
宣言
- 以下は、std
- atomic :: fetch_addの宣言です。
T fetch_add (T val, memory_order sync = memory_order_seq_cst) volatile noexcept;
C 11
T fetch_add (T val, memory_order sync = memory_order_seq_cst) noexcept;
- 以下は、std
- atomic :: fetch_add(アトミックテンプレート特殊化のメンバーのみ)の宣言です。
T fetch_add (ptrdiff_t val, memory_order sync = memory_order_seq_cst) volatile noexcept;
C 11
T fetch_add (ptrdiff_t val, memory_order sync = memory_order_seq_cst) noexcept;
パラメーター
- arg -それは算術加算の他の引数を入れて使用されます。
- order -値のメモリ順序を強制するために使用されます。
戻り値
この関数の効果の直前の値を、* thisの変更順で返します。
例外
*No-noexcept* -このメンバー関数は例外をスローしません。
例
- 以下のstd
- atomic :: fetch_addの例。
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<long long> data;
void do_work() {
data.fetch_add(1, std::memory_order_relaxed);
}
int main() {
std::thread th1(do_work);
std::thread th2(do_work);
std::thread th3(do_work);
std::thread th4(do_work);
std::thread th5(do_work);
th1.join();
th2.join();
th3.join();
th4.join();
th5.join();
std::cout << "Ans:" << data << '\n';
}
サンプル出力は次のようになります-
Ans:5