Cpp-standard-library-cpp-compare-exchange-weak

提供:Dev Guides
移動先:案内検索

C ++アトミックライブラリ-交換

説明

objが指す値をdesrの値でアトミックに置換し、obj→exchange(desr)のように、以前に保持されていた値objを返します。

objが指す値をdesrの値でアトミックに置き換え、obj→exchange(desr、order)のように、以前に保持されていた値objを返します。

宣言

以下は、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 );
以下は、std
atomic_exchange_explicitの宣言です。
template< class T >
T atomic_exchange_explicit( std::atomic<T>* obj, T desr,
                            std::memory_order order );

C 11

template< class T >
T atomic_exchange_explicit( volatile std::atomic<T>* obj, T desr,
                            std::memory_order order );

パラメーター

  • obj -変更するアトミックオブジェクトへのポインタで使用されます。
  • desr -アトミックオブジェクトに格納する値を使用します。
  • order -値のメモリ順序を同期するために使用されます。

戻り値

objが指すアトミックオブジェクトが以前に保持していた値を返します。

例外

*No-noexcept* -このメンバー関数は例外をスローしません。

以下のstd
atomic_exchangeおよびstd :: atomic_exchange_explicitの例では。
#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 0
Output from thread 0
Output from thread 0
Output from thread 0
Output from thread 0
Output from thread 0
Output from thread 0
Output from thread 0
Output from thread 0
....................