Re: volatile variable

From: David Woodhouse
Date: Mon Aug 11 2003 - 08:38:20 EST


On Fri, 2003-08-01 at 12:38, Richard B. Johnson wrote:
> First, there are already procedures available to do just
> what you seem to want to do, interruptible_sleep_on() and
> interruptible_sleep_on_timeout(). These take care of the
> ugly details that can trip up compilers.

Just in case there are people reading this who don't realise that
Richard is trolling -- do not ever use sleep_on() and friends. They
_will_ introduce bugs, and hence they _will_ be removed from the kernel
some time in the (hopefully not-so-distant) future.

> In any event in your loop, variable 'a', has already been
> read by the code the compiler generates. There is nothing
> else in the loop that touches that variable. Therefore
> the compiler is free to (correctly) assume that whatever
> it was when it was first read is what it will continue to
> be. The compiler will therefore optimise it to be a single
> read and compare. So, the loop will continue forever if
> 'a' started as zero because the compiler correctly knows
> that it cannot possibly change in the only execution
> path that it knows about.

If 'a' is a local variable that's true. If 'a' is a global as the
original poster explicitly declared, then the compiler must assume that
function calls (such as the one to schedule()) may modify it, and hence
may not optimise away the second and subsequent reads. Therefore, the
'volatile' is not required.

Richard, stop taunting the newbies :)

--
dwmw2

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/