再論sleep延時

背景

在做通信項目的時候需要處理不同線程的數據流匹配問題,在加入sleep(second)延時函數後發現表現有點奇怪,仔細查閱api說明才瞭解到Linux下sleep函數和windows下的不一樣!!!windows的sleep是毫秒延時,Linux下是秒級延時,而且輸入浮點數後是向下取整

Linux下延時函數彙總

sleep(int second)

秒級延時函數,輸入浮點數的話會直接向下取整。所以sleep(0.9)實際上等於沒有任何延時!(這正是我出bug 的緣由)

usleep(int usecond)

微秒級延時函數

跨平臺可用的毫秒延時函數

不要再糾結什麼平臺用什麼函數了,下面這個一勞永逸解決跨平臺延時問題

#ifdef WIN32
#include <windows.h>
#elif _POSIX_C_SOURCE >= 199309L
#include <time.h>   // for nanosleep
#else
#include <unistd.h> // for usleep
#endif
​
void sleep_ms(int milliseconds) // cross-platform sleep function
{
#ifdef WIN32
    Sleep(milliseconds);
#elif _POSIX_C_SOURCE >= 199309L
    struct timespec ts;
    ts.tv_sec = milliseconds / 1000;
    ts.tv_nsec = (milliseconds % 1000) * 1000000;
    nanosleep(&ts, NULL);
#else
    usleep(milliseconds * 1000);
#endif
}

參考鏈接

Is there an alternative sleep function in C to milliseconds

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章