首页 > 其他 > 详细

select实现精确定时器

时间:2014-11-17 21:23:13      阅读:339      评论:0      收藏:0      [点我收藏+]

select实现精确定时器

int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
struct timeval { long tv_sec; long tv_usec; } /* seconds and microseconds */


秒级定时器

void sec_sleep(unsigned sec) {
    int err;
    struct timeval tv;
    tv.tv_sec = sec;
    tv.tv_usec = 0;
    do {
           err = select(0, NULL, NULL, NULL, &tv);
    } while (err < 0 && errno == EINTR);
}


毫秒级定时器

void msec_sleep(unsigned long msec) {
    int err;
    struct timeval tv;
    tv.tv_sec = msec / 1000;
    tv.tv_usec = (msec % 1000) * 1000;
    do {
           err = select(0, NULL, NULL, NULL, &tv);
    } while (err < 0 && errno == EINTR);
}


微秒级定时器

void usec_sleep(unsigned long usec) {
    int err;
    struct timeval tv;
    tv.tv_sec = usec / 1000000;
    tv.tv_usec = usec % 1000000;
    do {
        err = select(0, NULL, NULL, NULL, &tv);
    } while (err < 0 && errno == ENTR);
}



select实现精确定时器

原文:http://my.oschina.net/keeplearn/blog/345664

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!