標籤:style blog color io 使用 ar div art sp
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