C 中的位域掩码
C 中是否有一种可移植的方法可以在编译时找出位字段的掩码?
理想情况下,我希望能够以原子方式清除这样的字段:
struct Reference {
unsigned age : 3;
unsigned marked : 1;
unsigned references : 4;
};
struct Reference myRef;
__sync_and_and_fetch(&myRef, age, ~AGE_MASK);
否则我必须取出结构上的锁,这比我想要的更重量级。
Is there a portable way in C to find out the mask for a bit field at compile time?
Ideally, I'd like to be able to atomically clear a field like this:
struct Reference {
unsigned age : 3;
unsigned marked : 1;
unsigned references : 4;
};
struct Reference myRef;
__sync_and_and_fetch(&myRef, age, ~AGE_MASK);
Otherwise I have to take out a lock on the struct, which is more heavyweight than I'd like.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
或者,如果你真的想要面具:
Or, if you really wanted the mask:
您可以执行以下操作:
要自动清除 myRef 的字段,请执行
(+ 当compare_and_swap 失败时要处理的未显示代码)
You could do something like:
To atomically clear a field of myRef, do
(+ unshown code to handle when compare_and_swap fails)
我不知道如何在编译时执行此操作,但在运行时,将位域结构的实例与适当大小的无符号整数联合起来应该是一个简单的问题,并将除您之外的所有字段设置为 0关心哪个应该设置为全 1——unsigned int 的值就是您想要的位掩码。您可以在启动时为每个字段执行此操作,也许可以使用宏来避免一些重复的代码。也许这还不够?
I don't know how to do it at compile time, but at runtime it should be a simple matter of union'ing an instance of your bitfield struct with an appropriately-sized unsigned int, and setting all fields to 0 except the one you care about which should be set to all 1s -- the value of the unsigned int is then the bitmask you want. You can do it for each field at startup, maybe with a macro to avoid some repetitive code. Might not that suffice?
我认为这是不可能的 - 即使使用 offsetof() ,它适用于字节偏移,但似乎不适用于位字段。我会将这些字段重新声明为枚举/定义(0x01 0x02 等)并自己管理这些位,这样您就可以获得原子更改。
I don't think is possible - even with offsetof() which works for byte offsets but does not seem to work for bitfields. I would redeclare the fields as enums/defines (0x01 0x02 etc) and manage the bits yourself, so you can get your atomic changes.
是的,这是可以做到的。您需要捕获该值并进行操作。然后,如果内存仍然包含旧值,则需要使用原子比较和交换(如 Windows 上的 InterlockedCompareExchange)来存储新值。如果有人修改了该值,您将循环并重试。请注意,这是一种标准模式,用于在内部函数不可用的情况下对字大小的数据进行任何操作。
下面的代码使用 int - 正如 Keith 指出的那样,您可以使用 union 来获取结构体的值作为 int。
Yes, this can be done. You need to capture the value and do the operation. Then you need to use an atomic compare and swap (like InterlockedCompareExchange on Windows) to store the new value if the memory still contains the old value. If someone modified the value, you loop and try again. Note this is a standard pattern for doing any operation on a word-sized piece of data where an intrinsic isn't available.
The code below uses an int - as Keith pointed out you can use a union to be able to get the values of the struct as an int.