具有易失性和非易失性成员的联合的语义是什么?
更具体地说,我有(简化)以下内容:
union foo
{
volatile int bits;
char data[sizeof(int)*CHAR_BIT];
}
如果我从未访问 data
的第一个 sizeof(int)
项,我可以依赖 bits
> 按预期工作吗?
More specifically, I have (simplified) the following:
union foo
{
volatile int bits;
char data[sizeof(int)*CHAR_BIT];
}
If I never access the first sizeof(int)
items of data
, can i rely on bits
working as expected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上将结构的字段之一标记为易失性是正确的。但你必须记住 volatile 关键字的作用。它告诉编译器不要优化对变量的访问。值始终从内存中读取,而不是从寄存器中的副本读取。
正如您在评论中所写,您正在尝试使内存分配线程安全。不幸的是,易失性并不能保证您可以从多个线程访问它。如果您使用8位CPU,访问整数值不是原子操作,因此您的程序将无法正常运行。
Basically marking one of the field of the structure as volatile is correct. But you have to remember what volatile keyword does. It tells the compiler to not optimize access to a variable. Value is always read from memory, not from its copy in register.
As you write in comment, you are trying to make memory allocation thread safe. Unfortunately volatile doesn't guarantee that you can access it from multiple threads. If you are using 8bit CPU, access to integer value is not atomic operation so your program will not work correctly.
易失性
对于实现锁毫无用处。我并不是在理论上谈论;而是在谈论。它将会失败,并且您将会遇到竞争条件,即使在单 CPU/单核环境中也是如此。制作真正的原子锁定原语的唯一方法是使用 cpu 的锁定原语(对于 x86,锁定前缀)编写程序集。实际上,可能有一种方法可以通过
易失性
来解决,但我知道的唯一这样的锁定机制需要O(n)
空间,其中n
是线程的数量,如果事先不知道可能的线程数量,那么它就毫无用处。volatile
is in no way useful for implementing locks. I'm not speaking just theoretically; it will fail and you will have race conditions, even on single-cpu/single-core environments. The only way to make real atomic locking primitives is to write assembly using the cpu's locking primitives (for x86, the lock prefix).Actually, there may be a way to get by with just
volatile
but the only such locking mechanism I know takesO(n)
space wheren
is the number of threads, which makes it pretty useless if the number of possible threads is not known in advance.