T
fetch_or(T operand,
memory_order order = memory_order_seq_cst) const noexcept; // (1) C++20
constexpr value_type
fetch_or(value_type operand,
memory_order order = memory_order_seq_cst) const noexcept; // (1) C++26
概要
OR演算を行う
テンプレートパラメータ制約
std::atomic_ref<T*>
の場合、型T
がオブジェクト型であること。型T
がvoid*
や関数ポインタであってはならない- C++26 :
is_const_v<T>
がfalse
であること
効果
order
で指定されたメモリオーダーにしたがって、現在の値にoperand
をORした値でアトミックに置き換える
戻り値
変更前の値が返される
例外
投げない
備考
- この関数は、
atomic_ref
クラスの整数型に対する特殊化で定義される。 - 符号付き整数型に対しては、符号なし整数型に変換されたかのようにしたあと演算が行われ、結果は符号付き整数型になる。未定義動作はない
例
基本的な使い方
#include <iostream>
#include <atomic>
#include <bitset>
int main()
{
int value = 0b1011;
std::atomic_ref<int> x{value};
x.fetch_or(0b1110);
std::cout << std::bitset<4>(value).to_string() << std::endl;
}
14
#include <iostream>
#include <atomic>
#include <bitset>
int main()
{
int value = 0b1011;
std::atomic_ref<int> x{value};
x.fetch_or(0b1110);
std::cout << std::bitset<4>(value).to_string() << std::endl;
}
出力
1111
複数スレッドからビット複合演算を行う例
#include <iostream>
#include <atomic>
#include <thread>
#include <bitset>
int main()
{
int value = 0b0110;
// 複数スレッドでビット複合演算を呼んでも、
// 最終的に全てのスレッドでのビット複合演算が処理された値になる
std::thread t1 {[&value] {
std::atomic_ref{value}.fetch_or(0b0001);
}};
std::thread t2 {[&value] {
std::atomic_ref{value}.fetch_or(0b1000);
}};
t1.join();
t2.join();
std::cout << std::bitset<4>(value).to_string() << std::endl;
}
24
std::cout << std::bitset<4>(value).to_string() << std::endl;
#include <iostream>
#include <atomic>
#include <thread>
#include <bitset>
int main()
{
int value = 0b0110;
// 複数スレッドでビット複合演算を呼んでも、
// 最終的に全てのスレッドでのビット複合演算が処理された値になる
std::thread t1 {[&value] {
std::atomic_ref{value}.fetch_or(0b0001);
}};
std::thread t2 {[&value] {
std::atomic_ref{value}.fetch_or(0b1000);
}};
出力
1111
バージョン
言語
- C++20
処理系
- Clang: 9.0 ❌
- GCC: 10.1 ✅
- Visual C++: ??
参照
- P3323R1 cv-qualified types in
atomic
andatomic_ref
- C++26でCV修飾されたテンプレート引数を受け取れるようになった
- P3309R3
constexpr atomic
andatomic_ref
- C++26で
constexpr
に対応した
- C++26で