std::atomic_fetch_or, std::atomic_fetch_or_explicit
From cppreference.com
| ヘッダー <atomic> で定義 |
||
| template< class T > T atomic_fetch_or( std::atomic<T>* obj, |
(1) | (C++11以降) |
| template< class T > T atomic_fetch_or( volatile std::atomic<T>* obj, |
(2) | (C++11以降) |
| template< class T > T atomic_fetch_or_explicit( std::atomic<T>* obj, |
(3) | (C++11以降) |
| template< class T > T atomic_fetch_or_explicit( volatile std::atomic<T>* obj, |
(4) | (C++11以降) |
アトミックに、objが指す値を、objの古い値とargとのビットごとのOR演算の結果で置き換えます。objが以前保持していた値を返します。
この操作は、以下が実行されるかのように行われます。
1,2) obj->fetch_or(arg)
3,4) obj->fetch_or(arg, order)
std::atomic<T>にfetch_orメンバがない場合(このメンバはboolを除く整数型にのみ提供されます)、プログラムはill-formed(不正な形式)となります。
目次 |
[編集] パラメータ
| obj | - | 操作対象のアトミックオブジェクトへのポインタ |
| arg | - | アトミックオブジェクトに格納されている値とビットごとのOR演算を行う値 |
| order | - | メモリ同期順序 |
[編集] 戻り値
*objの修正順序において、この関数の効果の直前の値。
[編集] 例
このコードを実行
#include <atomic> #include <chrono> #include <functional> #include <iostream> #include <thread> // Binary semaphore for demonstrative purposes only. // This is a simple yet meaningful example: atomic operations // are unnecessary without threads. class Semaphore { std::atomic_char m_signaled; public: Semaphore(bool initial = false) { m_signaled = initial; } // Block until semaphore is signaled void take() { while (!std::atomic_fetch_and(&m_signaled, false)) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void put() { std::atomic_fetch_or(&m_signaled, true); } }; class ThreadedCounter { static const int N = 100; static const int REPORT_INTERVAL = 10; int m_count; bool m_done; Semaphore m_count_sem; Semaphore m_print_sem; void count_up() { for (m_count = 1; m_count <= N; ++m_count) if (m_count % REPORT_INTERVAL == 0) { if (m_count == N) m_done = true; m_print_sem.put(); // signal printing to occur m_count_sem.take(); // wait until printing is complete proceeding } std::cout << "count_up() done\n"; m_done = true; m_print_sem.put(); } void print_count() { do { m_print_sem.take(); std::cout << m_count << '\n'; m_count_sem.put(); } while (!m_done); std::cout << "print_count() done\n"; } public: ThreadedCounter() : m_done(false) {} void run() { auto print_thread = std::thread(&ThreadedCounter::print_count, this); auto count_thread = std::thread(&ThreadedCounter::count_up, this); print_thread.join(); count_thread.join(); } }; int main() { ThreadedCounter m_counter; m_counter.run(); }
出力
10 20 30 40 50 60 70 80 90 100 print_count() done count_up() done
[編集] 不具合報告
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| P0558R1 | C++11 | 厳密な型一致が必要であったためTは複数の引数から推論された |
Tは推論されるのみobj から |
[編集] 関連項目
| 引数とアトミックオブジェクトの値との間でビット単位ORをアトミックに実行し、以前に保持されていた値を取得する ( std::atomic<T>のpublicメンバ関数) | |
| (C++11)(C++11) |
アトミックオブジェクトを非アトミックな引数とのビット単位ANDの結果で置き換え、アトミックオブジェクトの以前の値を取得する (関数テンプレート) |
| (C++11)(C++11) |
アトミックオブジェクトを非アトミックな引数とのビット単位XORの結果で置き換え、アトミックオブジェクトの以前の値を取得する (関数テンプレート) |
| C言語のドキュメント atomic_fetch_or, atomic_fetch_or_explicit
| |