首页 > 代码库 > sleep函数的BUG

sleep函数的BUG

BUGS
sleep() may be implemented using SIGALRM; mixing calls to alarm() and sleep() is a bad idea.

线程里面使用sleep函数来延时/定时是不安全的,原因是:sleep会受到SIGALARM信号的影响,如果在sleep()期间,有SIGALRM信号发送给线程,则立即返回,返回值是剩余的时间。

ps:sleep函数返回值:是一个无符号的整型,具体返回值是:若进程暂停到参数seconds 所指定的时间则返回0,若有信号中断则返回剩余秒数。

网上使用了条件变量来完成线程里面的延时,很不错哦~~如下例:

void thread_sleep(int second)  {      /*  time wait */      struct timespec outtime;      pthread_cond_t cond;      pthread_mutex_t mutex;        /*  timer init */      pthread_mutex_init(&mutex, NULL);       pthread_cond_init(&cond, NULL);        pthread_mutex_lock(&mutex);      outtime.tv_sec = time(NULL) + second;        outtime.tv_nsec = 0;      pthread_cond_timedwait(&cond, &mutex, &outtime);      pthread_mutex_unlock(&mutex);  } 

 

使用select来做延时,也很常用~不过分辨率是毫秒ms级别

看代码吧:

  

 1 #include <pthread.h> 2 #include <stdio.h> 3 #include <sys/signal.h> 4 #include <time.h> 5 #include <sys/time.h> 6  7 int mySleep(int sec, int msec) 8 { 9     struct timeval tv;10     tv.tv_sec = sec;11     tv.tv_usec = msec * 1000;12 13     select(0, NULL, NULL, NULL, &tv);14 15     return 0;16 }17 18 int main(int argc, char **argv)19 {20     int i, j;21     int ret;22 23     long int total_time;24     struct timeval tv_start, tv_current;25     while(1)26     {27         gettimeofday(&tv_start, 0);28         mySleep(0, 30);29         gettimeofday(&tv_current, 0);30         total_time = (tv_current.tv_usec - tv_start.tv_usec)/1000;31         printf("total time is %ld\n", total_time);32     }33     34     return 0;35 }

  okay,凑合着用用吧~~

 

sleep函数的BUG