有没有办法在给定的 int32_t 上重用 std::atomic?

Is there a way to reuse std::atomic on a given int32_t?

我有一个初始值为 42 的 int32_t。现在我希望它能被多个线程自动访问。

#include <atomic>

using namespace std;
int32_t* pn{};

int main()
{
    pn = getPtrFromMmap();    
    assert(42 == *pn); // note that *pn is mapped to a disk file

    // How to make the following two threads access *pn atomically?
    std::thread{[&]{ (*pn)++; }}.detach(); 
    std::thread{[&]{ (*pn)++; }}.detach();
}

编写正确的原子操作class并非易事。所以,我尝试用std::atomic来达到我的目的,但是失败了。

有没有办法在这种情况下重用std::atomic

没有

std::atomic大致认为是

template <typename T>
class atomic {
    T value;
public:
    // a bunch of member functions
};

即一个 std::atomic<int32_t> 包含 一个 int32_t.

你需要的是

template <typename T>
class atomic_ref {
    T & ref;
public:
    // a bunch of member functions
};

这种类型不是 std:: 的成员。

在 C++17 中,std::atomic<std::reference_wrapper<T>> 保证有效,但在这里没有帮助。对所指对象的操作不是原子的。