memcpy() safety on adjacent memory regions
I recently asked a question on using volatile and was directed to read some very informative articles from Intel and others discussing memory barriers and their uses. After reading these articles I have become quite paranoid though.
I have a 64-bit machine. Is it safe to memcpy into adjacent, non-overlapping regions of memory from multiple threads? For example, say I have a buffer:
char buff[10];
Is it always safe for one thread to memcpy into the first 5 bytes while a second thread copies into the last 5 bytes?
My gut reaction (and some simple tests) indicate that this is completely safe, but 开发者_开发百科I have been unable to find documentation anywhere that can completely convince me.
Safe, yes. Performant, no- in this limited example, at least. Remember that one cache line cannot be in two cores at once. You will force core A to wait while core B writes to the buffer, and then wait while the memory is transferred, and then write to it. Multi-core memory copies should be very large in size to avoid this effect.
Yes, it completely safe, serialization of access to the memory bus is done in hardware.
As long as each instance of memcpy believes it is writing into only its part of the buffer, it is completely safe. Array allocations of any form in C++ are very low-level; it is a contiguous block of storage allocated at the appropriate size for the program, and the array as an object that exists as anything other than a pointer is simply an illusion. Give memcpy non-overlapping ranges of the array, and it has no way of knowing that they aren't simply two completely separate arrays that just happen to be adjacent to each other. The writes won't interfere.
Yes this is totally unrelated to any kind of happens-before ordering. its just copying bytes around.
精彩评论