Tuesday, August 18, 2009

c++: memory update--atomic?

This is hardware specific and depends an the architecture. For x86 and x86_64 8 byte writes or reads are guaranteed to be atomic, if they are aligned. Quoting from the Intel Architecture Memory Ordering White Paper:

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.




The problem is not context switching, it is multicore and multicpu. – AProgrammer 9 hours ago
Even in multicore/multi cpu architecture physical memory access has to be serialised by the memory controller. It's electrically impossible to let multiple devices access the same circuitry at the same time duration. Memory controller accesses memory in blocks, and in whole units of data bus width, therefore it's not possible to have partial update of a memory location. – Indeera 8 hours ago
So what about if the double lies across the boundary of two cache lines? I doubt that MSVC++ will do that, because everything will be aligned to its size in powers of 2. But if you're generalising, it's not a requirement of the C++ standard (and in at least one of the ARM ABIs, longs and doubles only have to be 4-aligned, not 8-aligned). – onebyone 8 hours ago

No comments:

Post a Comment