Linux中的sleep、usleep、nanosleep、poll和select

栏目: C++ · 发布时间: 6年前

内容简介:在进行C/C++1) 基于

在进行 Linux C/C++ 编程时,可调用的 sleep 函数有好多个,那么究竟应当调用哪一个了?下表列出了这几个函数间的异同点,可作为参考:

性质

精准度

线程安全

信号安全

sleep

libc库函数

不能和alarm同时使用

有些是基于alarm实现的,所以不能和alarm同时使用

usleep

libc库函数

微秒

-

-

POSIX.1-2001已将usleep标注为废弃,POSIX.1-2008已删除usleep,应当使用nanosleep替代usleep

nanosleep

系统调用

纳秒

不确定

即使被信号中断,也可实现实际睡眠时长不小于参数指定时长

clock_nanosleep

系统调用

纳秒

不确定

区别于nanosleep,可选择为相对或绝对时间,其次是可以选择使用哪个时钟

poll

系统调用

毫秒

在协程库libco中可安全使用,如被信号中断,则实际睡眠时长会小于参数指定的时长

ppoll

系统调用

纳秒

如被信号中断,则实际睡眠时长会小于参数指定的时长

select

系统调用

微秒

即使被信号中断,也可实现实际睡眠时长不小于参数指定时长

pselect

系统调用

纳秒

如被信号中断,则实际睡眠时长会小于参数指定的时长

C/C++ 常用封装:

1) 基于 nanosleep 的毫秒级封装

#include 

void  millisleep (uint32_t milliseconds) {

struct timespec ts = {

milliseconds / 1000,

(milliseconds % 1000) * 1000000

};

while ((-1 == nanosleep(&ts, &ts)) && (EINTR == errno));

}

2) 基于 nanosleep 的微秒级封装

#include 

void  microsleep (uint32_t microseconds) {

struct timespec ts = {

microseconds / 1000000,

(microseconds % 1000000) * 1000

};

while ((-1 == nanosleep(&ts, &ts)) && (EINTR == errno));

}

3) 基于 poll 的秒级封装

// 可libco协程库中安全使用

void  pollsleep (int milliseconds) {

(void)poll(NULL, 0, milliseconds);

}

4) 基于 select 的毫秒级封装

void  selectsleep (int milliseconds) {

struct timeval timeout = {

milliseconds / 1000,

(milliseconds % 1000)

};

struct timeval old_timeout = { timeout.tv_sec, timeout.tv_usec };

while (true) {

(void)select(0, NULL, NULL, NULL, &timeout);

if (timeout.tv_sec<=0 && timeout.tv_usec<=0)

break;

}

}

如果开发环境是 C++11 或更高版本,则可直接使用 C++ 标准库提供的:

5) 毫秒睡眠

#if __cplusplus >= 201103L

#include 

#include 

#include 

std::this_thread:: sleep_for (std::chrono:: milliseconds (1000));

#endif // __cplusplus >= 201103L

6) 微秒睡眠

#if __cplusplus >= 201103L

#include 

#include 

#include 

std::this_thread:: sleep_for (std::chrono:: microseconds (1000));

#endif // __cplusplus >= 201103L

上述介绍的 sleep 函数均不方便控制它们提前结束,如果需要这种 sleep ,可基于 pthread_cond_timedwait实现,实现可参考 CEvent 源码:


以上所述就是小编给大家介绍的《Linux中的sleep、usleep、nanosleep、poll和select》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Machine Learning in Action

Machine Learning in Action

Peter Harrington / Manning Publications / 2012-4-19 / GBP 29.99

It's been said that data is the new "dirt"—the raw material from which and on which you build the structures of the modern world. And like dirt, data can seem like a limitless, undifferentiated mass. ......一起来看看 《Machine Learning in Action》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具