I found the following code, the out put is always:
std::atomic<A> is lock free? false
std::atomic<B> is lock free? true
This is the code:
struct A { int a[100]; };
struct B { int x, y; };
int main()
{
std::cout << std::boolalpha
<< "std::atomic<A> is lock free? "
<< std::atomic<A>{}.is_lock_free() << '\n'
<< "std::atomic<B> is lock free? "
<< std::atomic<B>{}.is_lock_free() << '\n';
}
I do not understand how can the second struct specialized atomic type be lock free and the 1st specialized atomic type cannot be lock free?
Thanks in advance.
http://en.cppreference.com/w/cpp/atomic/atomic_is_lock_free really explains it in the comment section. Memory alignment and register size may allow 2 packed ints to be handled in atomic way. In other word, 2 aligned ints are not different than a single long long on a 64bit system with 128bit register.
std::atomic
requires its template argument to be trivially copyable. That is, it knows that (load, store, etc.) operations on your struct B
simply copy bytes, and can be done with appropriate atomic instructions, if they are wide enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With