sizeof(atomic< t>)并不总是等于sizeof< t>
sizeof(atomic< t>)
的返回值并不总是等于sizeof(t)
的返回值,基于[atomics.generic.types.generic types.generic type ]/p9:
注意:原子专业化的表示不需要与其相应参数类型的大小相同。专业人士应尽可能具有相同的大小,因为这减少了将现有代码移植所需的努力
有时相等,例如:
struct A {
char i;
const char padding[3];
int j;
};
A a;
a.i = 1;
a.j = 2;
A b;
b.i = 3;
b.j = 4;
std::atomic<A> A_atomic(a);
sizeof(a_atomic)
为8,而sizef(a)
a_atomic.compare_exchange_weak(a,b)
返回true。
a_atomic.is_always_lock_free
返回true。
当我添加int
变量时,它们不相同:
struct A {
char i;
const char padding[3];
int j;
int k;
};
A a;
a.i = 1;
a.j = 2;
A b;
b.i = 3;
b.j = 4;
std::atomic<A> A_atomic(a);
sizeof(a_atomic)
为16,而size> sizeof(a)
是12
。代码> a_atomic.compare_exchange_weak(a,b)返回false。
a_atomic.is_always_lock_free
返回true。
当我添加int
时,std :: atomic&lt; a&gt;
发生了什么?
如何挑选两个结构之间的微妙差异来对齐内存布局以确保CAS返回正确?
我的环境是:
- macOSX10.13
- clang-900.0.0.37
- x86_64-apple-darwin18.7.0
更多信息:
我添加另一个int
actiake like:
struct A {
char i;
const char padding[3];
int j;
int k;
int h;
}
sizeof(a_atomic)
is 16,16,,和sizeof(a)
是16
。
a_atomic.is_always_lock_free
返回true。
The return value of sizeof(atomic<T>)
is not always equal to the return value of sizeof(T)
, based on following sentence from [atomics.types.generic]/p9:
Note: The representation of an atomic specialization need not have the same size as its corresponding argument type. Specializations should have the same size whenever possible, as this reduces the effort required to port existing code
Sometimes they are equal, like this:
struct A {
char i;
const char padding[3];
int j;
};
A a;
a.i = 1;
a.j = 2;
A b;
b.i = 3;
b.j = 4;
std::atomic<A> A_atomic(a);
sizeof(A_atomic)
is 8, and sizeof(A)
is 8 too.
A_atomic.compare_exchange_weak(a,b)
returns true.
A_atomic.is_always_lock_free
returns true.
When I add an int
variable, they are not the same:
struct A {
char i;
const char padding[3];
int j;
int k;
};
A a;
a.i = 1;
a.j = 2;
A b;
b.i = 3;
b.j = 4;
std::atomic<A> A_atomic(a);
sizeof(A_atomic)
is 16, and sizeof(A)
is 12.
A_atomic.compare_exchange_weak(a,b)
returns false.
A_atomic.is_always_lock_free
returns true.
What happened to std::atomic<A>
when I added an int
?
How can I pick out the subtle difference between the two structs to align the memory layout in order to ensure CAS returns true?
My environment is:
- macOSX10.13
- clang-900.0.37
- x86_64-apple-darwin18.7.0
more info:
I add another int
variable like:
struct A {
char i;
const char padding[3];
int j;
int k;
int h;
}
sizeof(A_atomic)
is 16, and sizeof(A)
is 16.
A_atomic.compare_exchange_weak(a,b)
returns true.
A_atomic.is_always_lock_free
returns true.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试
#pragma Pack(x)
(x是一个数字),以查看它如何影响大小。您可以查看 this 。You can try with
#pragma pack(x)
(x is a number) to see how it affects the size. You can look at this.