我是靠谱客的博主 敏感纸飞机,这篇文章主要介绍使用select接口写高精确延时,现在分享给大家,希望可以做个参考。

使用select接口写高精确延时。

select接口

int select(int maxfdp, fd_set *readset, fd_set *writeset, fd_set *exceptset,struct timeval *timeout);

原理

  • 利用select的timeout参数实现定时器;
  • 设置timeval的值,而将其他参数都置为NULL,当内部时间耗尽后select便会退出。

示例

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h> #include <sys/time.h> int main() { struct timeval tv; while(1) { tv.tv_sec = 1; // 定时1秒 tv.tv_usec = 0; switch(select(0, NULL, NULL, NULL, &tv)) { case -1: // 错误 printf("Error!n"); break; case 0: //超时 printf("timeout expires.n"); break; default: printf("defaultn"); break; } } return 0; }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
void usleep(unsigned long usec) { struct timeval tv; tv.tv_sec = usec / 1000000; tv.tv_usec = usec % 1000000; int err; do { err = select(0, NULL, NULL, NULL, &tv); } while(err < 0 && errno == EINTR); }

注意

  • 内核支持的延时分辨率一般不能达到微秒级;
  • 由于存在内核调度延时现象;
  • 内核分辨率一般为10ms的倍数。

最后

以上就是敏感纸飞机最近收集整理的关于使用select接口写高精确延时的全部内容,更多相关使用select接口写高精确延时内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部