Shaun Jackman
Wed Jan 26 19:45:00 GMT 2005

I've written a simple sleep function that depends on an incrementing
counter, _jiffies, and its rate, HZ. It busywaits, calling _sleep_hook
until either the timer expires or _sleep_hook returns -1, presumably
indicating a signal has interrupted the sleep. _jiffies is provided by
the user and most likely incremented by a timer interrupt service,
although it could be updated in _sleep_hook by some magic. If all the
newlib platforms support weak symbols, _sleep_hook could be a weak
symbol rather than a pointer to a function, though I think the latter
is probably more portable and flexible.

If HZ is undefined it returns immediately. Alternatively, sleep could
be left undefined, which is probably better, come to think of it, than
a defined function that does nothing useful whatsoever.

I'm not sure newlib is the ideal place for this code, but its
dependencies are few and provided by most common systems.


#include <time.h>

clock_t _jiffies;
int (*_sleep_hook)(clock_t elapsed, clock_t delay);

unsigned int
sleep(unsigned int seconds)
#if HZ
	clock_t now = _jiffies, delay = seconds * HZ, elapsed;
	while( (elapsed = _jiffies - now) < delay )
		if( _sleep_hook != NULL && _sleep_hook(elapsed, delay) == -1 )
	return (delay - elapsed) / HZ;
	return seconds;

More information about the Newlib mailing list