Exo*_*ist 5 c struct atomic padding compare-and-swap
程序在C中使用std = c99,这是在64位机器上.
struct epochs {
    volatile unsigned int epoch    : 1;
    volatile unsigned int pulse    : 1;
    volatile unsigned int active0  : 7;
    volatile unsigned int active1  : 7;
    volatile unsigned int counter0 : 24; 
    volatile unsigned int counter1 : 24; 
};
当我检查sizeof(epochs)它给了我12.
我可以告诉gcc不要通过添加__attribute((packed))来填充它; 所以我可以解决它.但是,我真的想知道为什么要添加4个字节来填充这个64位结构?
这里的主要内容是这个结构需要64位,因为它在64位原子交换操作中一次更新,当然这对12字节值不起作用.
oua*_*uah 13
volatile unsigned int epoch    : 1;
volatile unsigned int pulse    : 1;
volatile unsigned int active0  : 7;
volatile unsigned int active1  : 7;
^ 32位(4字节)
volatile unsigned int counter0 : 24; 
^ 32位(4字节)
volatile unsigned int counter1 : 24; 
^ 32位(4字节)
所以多4个字节.
C说:
(C99,6.7.2.1p10)"如果剩余足够的空间,则紧跟在结构中另一个位域之后的位域应被打包到同一单元的相邻位中"
没有足够的空间来把24位(counter0)更以32位为单位(可能是大小unsigned int在您的系统)已持有的16位(epoch,pulse,active0,active1).
您可以使用uin64_t而不是使用unsigned int以64位为单位打包您的位字段,但无论您的系统是否支持,它都是实现定义的.
(C99,6.7.2.1p4)"位字段的类型应为_Bool,signed int,unsigned int 或其他实现定义类型的限定或非限定版本."