在 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:
Instructions that read or write a single byte.
Instructions that read or write a word (2 bytes) whose address is aligned on a 2 byte boundary.
Instructions that read or write a doubleword (4 bytes) whose address is aligned on a 4 byte boundary.
- 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/