On Monday, 20 May 2013 at 06:53:34 UTC, Idan Arye wrote:
On Monday, 20 May 2013 at 05:39:42 UTC, Diggory wrote:
In your logic you're assuming that the order of operations is
maintained - without the correct memory barriers or
synchronisation both the compiler and CPU are free to
completely reorder any operations you do. That's why it's
always a bug to access mutable shared data without
synchronisation - any read not using some form of
synchronisation could give you back any value that the memory
is ever set to during the course of the program.
It can't be THAT chaotic. Neither the compiler nor the CPU will
perform a check on a value and then go back in time to fetch an
old version of that value and return it. This kind of behavior
would break non-threaded code.
Of course it's possible, for example the code may produce the
expected result if some invariant holds which does in fact hold
if there was a single thread running, but with multiple threads
the invariant is broken. Or more simply - the fact remains that
you are writing on one thread (correctly using synchronisation)
and reading from another (not using synchronisation) and
synchronisation is required on both the read and the write. The
compiler/CPU is then free to reorder the reads under the
assumption that the value won't change, and this assumption is
clearly wrong.
Basically most of your argument is just hoping that it will
behave the way you want, but without having any real guarantees,
and that's not the way to write thread-safe code, especially if
it's going to be part of the standard library.