c++ - 如何在多线程 C++ 17 程序中交换两个指针?

标签 c++ multithreading c++17

我有两个指针: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/

相关文章:

c++ - 在另一个进程中销毁共享的 std::vector

c++ - 将二进制对象读/写为十六进制?

c++ - 使用额外参数 boost 变体访问者

python - 如何在python中同时运行两个同步进程

c# - 什么时候使用多线程?

c++ - constexpr 模板参数的显式指定参数无效

c++ - 在 C++ 11 中将指针传递给临时变量?

c++ - 使用 glm 在本地和全局方向上旋转和平移对象

c++ - 映射和 For 循环

java - 以异步方式访问时,单例中的类级别变量是否会导致脏读?