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

Viewed 118

I have an int32_t with an initial value 42. Now I want it to be atomically accessed by multiple threads.

#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();
}

It is not a trivial task to write a correct atomic operation class. So, I tried to use std::atomic to achieve my goal, but failed.

Is there a way to reuse std::atomic in such a case?

1 Answers

No.

Think of std::atomic as roughly

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

I.e. a std::atomic<int32_t> contains an int32_t.

What you need is a

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

Such a type is not a member of std::.

In C++17 std::atomic<std::reference_wrapper<T>> is guaranteed to be valid, but it doesn't help here. Operations on the referent are not atomic.

Related