我有两个指针:pA 和 pB。它们指向两个大的哈希映射对象。
当pB指向的哈希图完全更新后,我想交换pB和pA。
在C++ 17中,如何快速且线程安全地交换它们?原子?我是 c++ 17 的新手。
2个指针的原子无等待交换可以通过以下方式实现:
#include <atomic>
#include <cstdint>
#include <cassert>
template<class T>
class Pointers2 {
uintptr_t const ab_;
std::atomic<uintptr_t> a_;
public:
Pointers2(T* a, T* b)
: ab_(reinterpret_cast<uintptr_t>(a) ^ reinterpret_cast<uintptr_t>(b))
, a_(reinterpret_cast<uintptr_t>(a))
{}
T* a() const { return reinterpret_cast<T*>(a_.load(std::memory_order_acquire)); }
T* b() const { return reinterpret_cast<T*>(a_.load(std::memory_order_acquire) ^ ab_); }
void exchange() { a_.fetch_xor(ab_, std::memory_order_release); }
};
int main() {
int a = 1, b = 2;
Pointers2<int> p2(&a, &b);
assert(p2.a() == &a);
assert(p2.b() == &b);
p2.exchange();
assert(p2.a() == &b);
assert(p2.b() == &a);
p2.exchange();
assert(p2.a() == &a);
assert(p2.b() == &b);
}
需要获取/释放内存顺序以确保写入共享数据T
不要重新排序过去exchange
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)