我有两个指针:pA 和 pB。它们指向两个大的 HashMap 对象。 当 pB 指向的 hash map 完全更新后,我想交换 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
之后重新排序。
关于c++ - 如何在多线程 C++ 17 程序中交换两个指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54557611/