C++ 原子庫 - exchange



描述

它會自動用非原子的引數替換原子物件的數值,並返回原子物件的舊值。

宣告

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

異常

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
.....................
atomic.htm
廣告
© . All rights reserved.