Re: 32-bit memory accesses on dual-core dual-Xeon processors
Tom Widmer [VC++ MVP] skrev:
Bruno van Dooren [MVP VC++] wrote:
I knew there was something simple missing from the implementation that I
had.
I forgot to make sure that the compiler itself would not reorder any of
the
memory operations.
Instead of declaring everything as volitile, wouldn't it also be possible
to
disable optimizations for the read and write functions themselves (or
potentially all of the methods for the queue to be safe)? The queue that I
have completey encapsulates the internal variables, so there is no way to
modify the queue except through specific methods.
Not on a per-function basis AFAIK.
But it is possible to disable optimizations for a given code file. That
might work as well, but I don't know of that can prevent all problems. the
volatile keyword was invented just for this purpose.
I don't think it was invented for multithreading. I think it was for
hardware registers, ISRs, signal handlers, etc.
Exactly. Now if you read the MSDN documentation, threads are mentioned,
implying that memory barriers are somehow inserted into the code. A
quick examination of the assembly output confirmed my suspicion that
no such code is generated.
It also makes you code
easier to understand, since anyone reading the sources will see which
variables are prone to be updated asynchronously.
On the other hand, you can be even more explicit by leaving out volatile
and inserting appropriate memory barriers (which also act as barriers
against the optimizer performing incorrect reorderings). That way, the
explicit ordering requirements of the code are documented. Even better,
you can use an atomic<T> type class.
I agree with you completely here, and must add that I hope the
"lock-free" code will not ever be attempted to be used by anyone -
except perhaps as a scary example of what not to do.
I did not know that there exists an atomic<T> for MSVC. Is that
something that is part of the emerging C++0x standard?
/Peter