Cpp-standard-library-cpp-exchange
提供:Dev Guides
C ++アトミックライブラリ-交換
説明
アトミックオブジェクトの値をアトミックに置き換え、以前保持されていた値を取得します。
宣言
- 以下は、std
- atomic :: exchangeの宣言です。
T exchange( T desired, std::memory_order order = std::memory_order_seq_cst );
C 11
T exchange( T desired, std::memory_order order = std::memory_order_seq_cst ) volatile;
パラメーター
- 望ましい-値を割り当てるために使用されます。
- order -メモリ順序の制約を強制するために使用されます。
戻り値
呼び出しの前にアトミック変数の値を返します。
例外
*No-noexcept* -このメンバー関数は例外をスローしません。
例
- 以下のstd
- atomic :: exchangeの例。
#include <iostream>
#include <atomic>
#include <thread>
#include <vector>
std::atomic<bool> ready (false);
std::atomic<bool> winner (false);
void count1m (int id) {
while (!ready) {}
for (int i=0; i<1000000; ++i) {}
if (!winner.exchange(true)) { std::cout << "thread #" << id << " won!\n"; }
};
int main () {
std::vector<std::thread> threads;
std::cout << "spawning 10 threads that count to 1 million...\n";
for (int i=1; i<=10; ++i) threads.push_back(std::thread(count1m,i));
ready = true;
for (auto& th : threads) th.join();
return 0;
}