具有易失性和非易失性成员的联合的语义是什么?

发布于 2024-09-11 12:55:15 字数 235 浏览 2 评论 0原文

更具体地说,我有(简化)以下内容:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

盗琴音 2024-09-18 12:55:15

基本上将结构的字段之一标记为易失性是正确的。但你必须记住 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.

她说她爱他 2024-09-18 12:55:15

易失性对于实现锁毫无用处。我并不是在理论上谈论;而是在谈论。它将会失败,并且您将会遇到竞争条件,即使在单 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 takes O(n) space where n is the number of threads, which makes it pretty useless if the number of possible threads is not known in advance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文