sleep, usleep 函数延时的问题

sleep, usleep 函数延时的问题

问题

多进程、多线程环境下,期望线程睡眠 usleep(500*1000), 实际上sleep函数会因为中断、system调用等被立即唤醒。

【注】 POSIX.1-2001已将usleep标注为废弃,POSIX.1-2008已删除usleep,应当使用nanosleep替代usleep ( Linux中的sleep、usleep、nanosleep、poll和select

API

  • API
    #include <unistd.h>
    int usleep(useconds_t usec);
    
  • 返回值
    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.
    

解决

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;
}

参考

猜你喜欢

转载自blog.csdn.net/hylaking/article/details/106265402