"Ian Collins" <ia******@hotmail.coma écrit dans le message de news:
5r*************@mid.individual.net...
ju**********@yahoo.co.in wrote:
>Guys,
Please have a look at the following piece of code:
int gcount = 0;
int gdelay = 0;
/* both gcount and gdelay are changed outside this function by an
interrupt handler code */
somefunc()
{
int count = gcount;
while (count == gcount || gdelay != 0) {
/*some handling */
}
}
I am quite sure that "gcount" should be declared volatile so that
compiler doesn't optimise the condition "count == gcount".
However, I am not sure if "gdelay" should also be declared to be
volatile ?
Any variable that can be changed in another context should be declared
extern. The compiler could see that gdelay is initialised to 0 and
optimise away the expression...
nonsense! As long as they are not static, variables defined at global scope
*have* extern linkage.
Furthermore, the interrupt code could be in the same module, for instance in
the form of a signal handler, and these global variables could be made
static then.
Both gcount and gdelay should be declared volatile to account for what the
OP is describing. Incidentally, it may not be sufficient if accessing them
is not guaranteed to be an atomic operation. See sections 7.14 on signal
handling for a discussion of type sig_atomic_t. 7.18.3p3 only guarantees
that type sig_atomic_t support at least 255 different values.
To make matters worse, if your "interrupt" code modifies both gcount and
gdelay, you need further non trivial code to ascertain that the values used
in somefunc() be consistent, because the "interrupt" could occur between the
access to one and the other, or even in the middle of such an access (from
the previous paragraph).
Interrupt handling, and thread programming, is *very* tricky to do right.
Your code may seem to work for a long time before conditions occur that make
it fail. It better not be at the heart of an anti-lock braking system, an
air-bag trigger, or any kind of critical device control unit... This group
is not the best place to discuss these issues, but I recommend that you use
proven techniques to deal with your "interrupt" handling issues.
--
Chqrlie.