mercredi 4 mars 2020

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

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?

Aucun commentaire:

Enregistrer un commentaire