Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the struct specialized atomic type be lock free?

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.

like image 448
lightrek Avatar asked Mar 09 '23 04:03

lightrek


2 Answers

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.

like image 113
Kaveh Vahedipour Avatar answered Mar 10 '23 18:03

Kaveh Vahedipour


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.

like image 44
Brian Bi Avatar answered Mar 10 '23 17:03

Brian Bi