c++ - 更新双操作是原子的

标签 c++ visual-c++

在 Java 中,更新 double 和 long 变量可能不是原子的,因为 double/long 被视为两个独立的 32 位变量。

http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#28733

在 C++ 中,如果我使用 32 位 Intel 处理器 + Microsoft Visual C++ 编译器,更新双(8 字节)操作是原子的吗?

我找不到太多关于此行为的规范。

当我说“原子变量”时,我的意思是:

线程 A 试图将 1 写入变量 x。 线程 B 试图将 2 写入变量 x。

我们将从变量 x 中获取值 1 或 2,但不是未定义的值。

最佳答案

这是特定于硬件的,取决于架构。对于 x86 和 x86_64,8 字节写入或读取保证是原子的,如果它们对齐的话。引用自英特尔架构内存订购白皮书:

Intel 64 memory ordering guarantees that for each of the following memory-access instructions, the constituent memory operation appears to execute as a single memory access regardless of memory type:

  1. Instructions that read or write a single byte.

  2. Instructions that read or write a word (2 bytes) whose address is aligned on a 2 byte boundary.

  3. Instructions that read or write a doubleword (4 bytes) whose address is aligned on a 4 byte boundary.

  4. Instructions that read or write a quadword (8 bytes) whose address is aligned on an 8 byte boundary.

All locked instructions (the implicitly locked xchg instruction and other read-modify-write instructions with a lock prefix) are an indivisible and uninterruptible sequence of load(s) followed by store(s) regardless of memory type and alignment.

关于c++ - 更新双操作是原子的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1292786/

相关文章:

c++ - 如何从注册表中读取本地化名称?

c++ - 接受停靠栏图标上的文件拖放

c++ - 通过 ZeroMQ 以字符串形式接收对象然后通过另一个套接字以零拷贝发送它的正确方法是什么?

c++ - 中断正在执行 MKL 或其他第三方函数的线程

c# - 如何在 C# 或 C++ 中使用条件语句检查/比较四个变量是否相同或不同

c++ - 生成控制台窗口而不锁定应用程序

c++ - 私有(private)方法实现编译报错

c++ - 需要澄清类的虚函数和私有(private)成员

visual-c++ - 从 DLL 导出函数 - 使用 DEF 文件或 dllexport?

c# - 如何在 Visual C#/C++ 中实现文本转语音 (TTS)?