Page 1 of 1

Timer rollovers?

Posted: Mon Feb 16, 2009 10:41 pm
by earlz
Hello, I am wondering what is a good way to deal with timer variable roll-overs. like with this...

Code: Select all

uint32_t timer=0;
void timer_irq(){
timer++;
}
....
void wait(uint32_t time){
uint32_t p=timer;
while(p<timer);
}
Well, if timer rolls over to zero during the wait function, then u have a infinite loop. How do you avoid this? especially in userland when there are applications that do things like get_timerticks() and then do a loop waiting for timer to become greater...

is there a kernel way to do this? or is it just something application programmers should be aware of?

Re: Timer rollovers?

Posted: Mon Feb 16, 2009 10:55 pm
by michael1234
why not use a 64bit variable to keep track of the number of ticks?

Thats over a million years before you have to worry about the timer rollover :wink:

Re: Timer rollovers?

Posted: Tue Feb 17, 2009 3:27 am
by pcmattman
Or even keep track of when an overflow does occur, and increment a variable numOverflows or something.

Granted, it could make the algorithms a little more tricky.

A (not necessarily better, but another) way:

Code: Select all

uint32_t timer=0;
void timer_irq(){
timer++;
}
....
void wait(uint32_t time){
uint32_t p=timer;
uint32_t end = timer + time; // this will allow overflow
while(p != end);
}

Re: Timer rollovers?

Posted: Tue Feb 17, 2009 4:02 am
by AJ
Hi,

I just feel I should point out to anyone using the above snippet that if the process gets no run time during the period where p == end (very likely), this process will go in to an infinite loop.
pcmattman wrote:Or even keep track of when an overflow does occur, and increment a variable numOverflows or something.
If timer is a 32 bit value and numOverflows is a 32 bit value, you could just take michael1234's suggestion and use a 64 bit variable to start with (on architectures that support it).

Cheers,
Adam

Re: Timer rollovers?

Posted: Tue Feb 17, 2009 4:07 am
by pcmattman
I just feel I should point out to anyone using the above snippet that if the process gets no run time during the period where p == end (very likely), this process will go in to an infinite loop.
A valid point, and a definite fault in the snippet I posted above.

Realistically you would want to have the process put onto a sleep queue and every timer interrupt check the sleep queue to find if a process needs to be woken. At least, that's one (/yet another) way of doing it :P.