Re: WaitForSingleObject() will not deadlock
On Sat, 07 Jul 2007 13:28:58 -0700, Frank Cusack <fcusack@fcusack.com>
wrote:
On Sat, 07 Jul 2007 12:28:50 -0400 Joseph M. Newcomer <newcomer@flounder.com> wrote:
For example
x = 2;
CreateThread()
x = 3;
has the characteristic that there are two sequential assignments of
values to x, and no intervening use of x. Therefore, the compiler
should be free to migrate the assignment of x=3 backward and
eliminate x=2 entirely, or migrate the assignment x=3 forward and
also eliminate x=2 entirely.
No! The compiler is absolutely not allowed to do that. This is not
even a thread thing.
For the moment, let's pretend CreateThread() is rand() or something, so
that threads unequivocally are not in the picture:
The x comes from my example, which declared it like this:
Because x is not volatile, the compiler can reorder or even eliminate the
assignments if it can prove it does not alter the "observable behavior" of
the program (C++ Standard 1.9). Of course, for all the compiler knows,
rand() (or CreateThread) does a printf(x), and since that's "observable
behavior", it has to perform the assignment "x = 2" before calling rand()
and can't move "x = 3" above the rand() call. Coincidentally, and let me
stress for Joe, COINCIDENTALLY, this also tends to help multithreaded code,
because typically the compiler cannot see into functions like CreateThread
and mutex operations so must assume they can use x in ways that affect
"observable behavior". This prevents it from caching data across function
calls when that data is potentially reachable from those functions, forces
it to perform writes, which in program sequence come before the operation,
before performing the operation, and similarly for reads. Joe would call
this "conservative", but to me, "conservative" implies a choice, and there
is none here, so I think of it as simply "correct". Of course, things are
even weirder at the hardware level, and memory barriers may have to be used
to keep the hardware in line.
--
Doug Harrison
Visual C++ MVP