Search code examples
c++c++11atomicstdatomic

Is there a way to perform atomic operations on a non-atomic object?


I have a struct that contains an integer (say int m_ref) denoting an internal reference count.

In order to maintain C compatibility I can't change the type to std::atomic<int>: the struct may only contain plain old data.

However, I want to adjust my code to exploit the atomic features now in C++11; namely I need to accomplish:

++m_ref;

and

--m_ref;

as atomic operations. I'm currently using assembler (Intel bus locks) to do this but that code is hardly portable and I'm keen to remove it now that C++ offers a standard construct.

Somehow I need to get to 'under the hood' and do what atomic<T> does but without the overhead of creating an atomic type: I fear that attaching m_ref to atomic<T> will degrade performance.

I suspect this is quite standard and I'm missing something simple here.


Solution

  • With atomic_ref since C++20, you can do it like this:

    #include <atomic>
    
    void add(int& a)
    {
        std::atomic_ref(a).fetch_add(1);
    }