Sleep, usleep function delay problem
problem
In a multi-process and multi-threaded environment, the thread is expected to sleep usleep (500*1000). In fact, the sleep function will be awakened immediately due to interrupts, system calls, etc.
[Note] POSIX.1-2001 has marked usleep as obsolete, and POSIX.1-2008 has deleted usleep. You should use nanosleep instead of usleep ( sleep, usleep, nanosleep, poll and select in Linux )
API
- API
#include <unistd.h> int usleep(useconds_t usec);
- return value
returns 0 on success. On error, -1 is returned, with errno set to indicate the cause of the error.
- ERRORS
EINTR Interrupted by a signal; see signal(7). EINVAL usec is greater than or equal to 1000000.
solve
int microsleep(unsigned int microseconds)
{
unsigned int eclipsed = 0;
struct timeval bgn,end;
gettimeofday(&bgn,0);
do {
while (microseconds > eclipsed && usleep(microseconds - eclipsed) < 0 && errno == EINTR);
gettimeofday(&end,0);
eclipsed = (end.tv_sec - bgn.tv_sec) * 1000 + (end.tv_usec - bgn.tv_usec) / 1000;
} while (eclipsed < microseconds);
return 0;
}