名前空間
変種
操作

std::atomic_fetch_sub, std::atomic_fetch_sub_explicit

提供: cppreference.com
< cpp‎ | atomic
 
 
 
ヘッダ <atomic> で定義
(1)
template<class T >

T atomic_fetch_sub(std::atomic<T>* obj,

                    typenamestd::atomic<T>::difference_type arg )noexcept;
template<class T >

T atomic_fetch_sub(volatilestd::atomic<T>* obj,

                    typenamestd::atomic<T>::difference_type arg )noexcept;
(2)
template<class T >

T atomic_fetch_sub_explicit(std::atomic<T>* obj,
                             typenamestd::atomic<T>::difference_type arg,

                             std::memory_order order )noexcept;
template<class T >

T atomic_fetch_sub_explicit(volatilestd::atomic<T>* obj,
                             typenamestd::atomic<T>::difference_type arg,

                             std::memory_order order )noexcept;

アトミック減算を行います。 obj の指す値から arg をアトミックに減算し、 obj がそれまで保持していた値を返します。 この操作は以下のコードが実行されたかのように行われます。

1)obj->fetch_sub(arg)
2)obj->fetch_sub(arg, order)

目次

[編集]引数

obj - 変更するアトミック変数を指すポインタ
arg - アトミック変数に格納されている値から減算する値
order - この操作に対するメモリ同期順序付け。 すべての値を指定できます。

[編集]戻り値

*obj変更順序における、この関数の効果の直前の値。

[編集]実装例

template<class T > T atomic_fetch_sub(std::atomic<T>* obj, typenamestd::atomic<T>::difference_type arg )noexcept{return obj->fetch_sub(arg);}

[編集]

インデックス付きコンテナを複数のスレッドで並行的に処理するために fetch_sub を使用します。

#include <string>#include <thread>#include <vector>#include <iostream>#include <atomic>#include <numeric>   constint N =50;std::atomic<int> cnt;std::vector<int> data(N);   void reader(int id){for(;;){int idx = atomic_fetch_sub_explicit(&cnt, 1, std::memory_order_relaxed);if(idx >=0){std::cout<<"reader "<<std::to_string(id)<<" processed item "<<std::to_string(data[idx])<<'\n';}else{std::cout<<"reader "<<std::to_string(id)<<" done\n";break;}}}   int main(){std::iota(data.begin(), data.end(), 1); cnt = data.size()-1;   std::vector<std::thread> v;for(int n =0; n <5;++n){ v.emplace_back(reader, n);}for(auto& t : v){ t.join();}}

出力:

reader 2 processed item 50 reader 1 processed item 44 reader 4 processed item 46 <....> reader 0 done reader 4 done reader 3 done

[編集]欠陥報告

以下の動作変更欠陥報告は以前に発行された C++ 標準に遡って適用されました。

DR 適用先 発行時の動作 正しい動作
P0558R1 C++11 exact type match required because T is deduced from multiple arguments T is deduced from the atomic argument only

[編集]関連項目

アトミックオブジェクトに格納されている値から引数の値をアトミックに減算し、以前保持されていた値を取得します
(std::atomic<T>のパブリックメンバ関数)[edit]
アトミックオブジェクトに非アトミック値を加算し、そのアトミックの以前の値を取得します
(関数テンプレート)[edit]
atomic_fetch_sub, atomic_fetch_sub_explicitC言語リファレンス
close