如何在多线程c ++ 17程序中交换两个指针? [英] How to swap two pointers in multi-threaded c++ 17 program?
本文介绍了如何在多线程c ++ 17程序中交换两个指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个指针:pA和pB。他们指向两个大的哈希图对象。
由pB指向的哈希映射被完全更新时,我想交换pB和pA。
I have two pointers: pA and pB. They points to two big hash map objects. when the hash map pointed by pB is updated completely, I want to swap pB and pA.
在C ++ 17中,如何快速交换它们和线程安全?原子?我是c ++ 17的新手。
In C++ 17, how to swap them fast and thread safe? Atomic? I am new to c++ 17.
推荐答案
2个指针的原子无等待交换可以通过以下方式实现:
Atomic wait-free exchange of 2 pointers can be implemented in the following manner:
#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
不会在交换
之后重新排序。
Acquire/release memory ordering is required to make sure that writes to shared data T
do not get reordered past exchange
.
这篇关于如何在多线程c ++ 17程序中交换两个指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文