Re: Should I use mutex in this context?
On Wed, 29 Oct 2008 16:45:41 -0400, Tommy <tommy767@gmail.com> wrote:
Ben Voigt [C++ MVP] wrote:
Tommy wrote:
I really hope this is not true. I simply can't believe this.
There is no change in logic (as long as the compiler can prove that
someglobal isn't changed by the loop body or any function it calls -- it
pays no attention to other threads). The compiler has preserved the
semantics of *sequential* execution as required.
Think about this one:
int a[1000]
for( int i = 0; i < x * y + z - 72; i++ ) {
a[i] = i;
}
The compiler changes this to:
int a[1000];
const int u = x * y + z - 72;
for( int i = 0; i < u; i++ )
a[i] = i;
saving a multiplication, addition, and subtraction on every iteration of the
loop. Of course if the body of the loop changes x, y, or z then the
compiler can't do this any more.
That makes sense because there is no change in flow and as long as the
end result is the same, no problem.
That is not the case in the stated claim:
while(X) { ...}
is fundamentally not the same as:
if (X) do { ....} while(TRUE);
It just isn't. I really, really, really hope this is not true.
If "X" is the aforementioned "someglobal", and "X" is provably unreachable
from the loop bodies, the compiler is free to read the value of X once,
cache it, and use the cached value from then on. However, if the loop
bodies contain a function call, say, to some function residing in an opaque
DLL, perhaps EnterCriticalSection, the compiler cannot see into that
function, and thus it cannot prove (at least in the cases that matter) that
function does not access X. IOW, after the compiler's knowledge of X's
value is potentially compromised, the compiler has to reload X the next
time it reads it.
This fact, which is actually a property of the sequential execution model,
causes a lot of correct behavior to fall out naturally for multithreaded
programs WRT code motion around things like mutex lock/unlock operations.
And if the compiler's intelligence were to grow exponentially such that it
could determine that X is unreachable, compiler implementers would have to
start marking the mutex lock/unlock and various other operations to prevent
optimizing around them.
--
Doug Harrison
Visual C++ MVP