Cpp-standard-library-cpp-atomic-exchange
提供:Dev Guides
C ++アトミックライブラリ-交換
説明
アトミックオブジェクトの値を自動的に非アトミック引数に置き換え、アトミックの古い値を返します。
宣言
- 以下は、std
- atomic_exchangeの宣言です。
template< class T >
T atomic_exchange( std::atomic<T>* obj, T desr );
C 11
template< class T >
T atomic_exchange( volatile std::atomic<T>* obj, T desr );
パラメーター
- obj -変更するアトミックオブジェクトへのポインタで使用されます。
- desr -値をアトミックオブジェクトに格納するために使用されます。
- order -この操作のメモリ順序を同期するために使用されます。
戻り値
objが指すアトミックオブジェクトが以前に保持していた値を返します。
例外
*No-noexcept* -このメンバー関数は例外をスローしません。
例
- 以下のstd
- atomic_exchangeの例。
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
std::atomic<bool> lock(false);
void f(int n) {
for (int cnt = 0; cnt < 100; ++cnt) {
while(std::atomic_exchange_explicit(&lock, true, std::memory_order_acquire))
;
std::cout << "Output from thread " << n << '\n';
std::atomic_store_explicit(&lock, false, std::memory_order_release);
}
}
int main() {
std::vector<std::thread> v;
for (int n = 0; n < 10; ++n) {
v.emplace_back(f, n);
}
for (auto& t : v) {
t.join();
}
}
出力は次のようになります-
Output from thread 0
Output from thread 1
Output from thread 0
Output from thread 1
Output from thread 0
Output from thread 1
Output from thread 0
Output from thread 1
.....................