C++ 原子庫 - exchange



描述

它以原子方式將 obj 指向的值替換為 desr 的值,並返回 obj 以前儲存的值,如同透過 obj → exchange(desr) 一樣。

它以原子方式將 obj 指向的值替換為 desr 的值,並返回 obj 以前儲存的值,如同透過 obj → exchange(desr, order) 一樣。

宣告

以下是 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 指向的原子物件以前儲存的值。

異常

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
....................
atomic.htm
廣告