Technically the volatile keyword doesn't even solve this problem; it just so happens that on
most compilers it does, but the behavior of the compiler in this regard is not mandated by
the standard.
The only sure-fire way to solve the problem is to use a synchronization object such as a
mutex or semaphore.
@xagutxu:
The reason why you see the apparent inexplicable behavior is because when the compiler
sees the code
1 2 3 4
|
while( some_variable == 0 )
{
// do nothing
}
|
the compiler is saying to itself "well, nothing in the loop can ever modify some_variable, so
in theory, I can optimize out the second and all subsequent comparisons, since once I get
into the loop, there is no way to get out of it."
When you put the "cout << '.';" statement in the loop, suddenly the compiler cannot make
that assumption because,
in theory ostream& operator<<( char )
could modify
some_variable, so the compiler can no longer elide the comparisons.