C++ Atomic 库 - 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 指向的原子对象先前保存的值。
异常
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 .....................