如何将结构体成员对齐到特定边界。动机之一是禁用错误共享。
考虑这个例子:
use std::sync::atomic::AtomicBool;
pub struct Foo {
id: String,
read: AtomicBool,
#[repr(align(64))]
write: AtomicBool
}
error[E0517]: attribute should be applied to a struct, enum, function, associated function, or union
--> src/lib.rs:5:12
|
5 | #[repr(align(64))]
| ^^^^^^^^^
6 | write: AtomicBool
| ----------------- not a struct, enum, function, associated function, or union
For more information about this error, try `rustc --explain E0517`.
创建包装类型:
use std::sync::atomic::AtomicBool;
#[repr(align(64))]
struct CacheAligned<T>(T);
#[repr(C)]
pub struct Foo {
id: String,
read: AtomicBool,
write: CacheAligned<AtomicBool>,
}
如果您对特定布局感兴趣,还应该使用
#[repr(C)]
;否则布局未指定。