Re: 32-bit memory accesses on dual-core dual-Xeon processors
Bruno van Dooren [MVP VC++] <bruno_nos_pam_van_dooren@hotmail.com>
wrote:
I have an implementation for a circular buffer (a fixed-sized queue
of pointers) where there is only one producer and one consumer, each
running independently in different threads. There is currently no
protection (locking) because there are no variables that can be
written to by both threads simultaneously. The head and/or tail
could be read by one thread and
written by the other, but logically, there are no issues as long as
whole 32-bit quantities can be accessed.
Is there anything wrong with the assumptions I've made, especially
when the
code is run on dual-core dual-Xeon processors? Is memory on these
64-bit processors accessed in such a way that there could be a
memory corruption?
I have used that construct myself. it is perfectly safe on 32 bit
platforms or 64 bit platforms because the reads and writes of a 32
bit variable are executed atomically. i.e. you won't read a half
written 32 bit variable. cache coherency should be taken care of by
the chipset / cpus.
Note that some architectures feature weak cache coherence - I'm not sure
whether or not Xeon is one of them. One of the effects of weak coherence
is write reordering - writes executed by one CPU in a certain order may
appear to another CPU as if they were actually executed in a different
order. Consider:
void PushToQueue(item) {
*tail = item;
tail++; // assuming tail points one-past-the-last-element
}
The consumer may observe tail++ before observing *tail=item. In other
words, it may believe that a new element is available, and read garbage
from the new index before the new item has been placed there. One needs
to use memory barriers (or interlocked operations, or proper locking) to
avoid this effect.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925