简体   繁体   中英

Using atomic operations on a normal integer in C++

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.

You cannot use atomic operations on a non-atomic type in C++11. You must use std::atomic<int> or std::atomic_int to get atomic operations on an integer. Casting an int to std::atomic<int> is undefined behaviour.

If you have a C11 compiler as well as a C++11 compiler then you can use atomic_int in both cases (with a suitable using declaration for C++). If the compilers are compatible then everything will "just work".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM