sleep函數的BUG

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.