So in C++, say that I have the following 16 byte type, which can undergo atomic operations on CPUs that have the cmpxchg16b
instruction:
#include <atomic>
#include <cstdio>
struct foo
{
size_t _x;
void* _y;
foo(size_t x = 3, void* y = nullptr): _x(x), _y(y){}
};
int main()
{
std::atomic<foo> f1;
foo f2;
foo f3(2, new int(4));
f1.compare_exchange_strong(f2, f3);
std::printf("is always lock free %s\n", std::atomic<foo>::is_always_lock_free ? "true" : "false" );
}
However, say that I might want to do an atomic increment only on _x
, such as via fetch_add
. How do i apply such an atomic operation without having to use std::atomic<size_t>
? The reason I don't want to use that here is because then the larger foo
type becomes not trivially copyable, and prevents me from using the 16 byte compare and exchange, giving the following error:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/atomic:923:3: error:
_Atomic cannot be applied to type 'foo' which is not trivially copyable
_Atomic(_Tp) __a_value;
So i am looking for a way to do something like,
foo a1;
fetch_add(&a1._x);