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
广告