c++ - 可以将 struct timespec 重用于 nanosleep 吗?

标签 c++ c sleep

我的程序计划循环以从队列中获取一些元素,但是,继续循环可能会导致 CPU 使用率过高,我想知道是否要等待 1 毫秒才能进入 nanosleep。我可以只在全局上制作 struct timespec shared_time_wait; 并重用它吗?

struct timespec shared_time_wait;

void wait1ms()
{   
    nanosleep(&shared_time_wait, NULL);
}

void init() {
 unsigned int ms = 1;
 shared_time_wait.tv_sec = ms / (1000 * 1000);
 shared_time_wait.tv_nsec = (ms % (1000 * 1000)) * 1000;

 for(;;) {
  wait1ms();
 }
}

最佳答案

来自 man 2 nanosleep :

int nanosleep(const struct timespec *req, struct timespec *rem);

重用 req 非常好,因为它被声明为 const。由于您没有自己更改它,并且该函数的 const 特性意味着它也没有更改它,因此重用它不会有任何坏处。 (以上内容对于 rem 不成立,因为它已被写入,但您没有使用它,所以您不必担心它。)

关于c++ - 可以将 struct timespec 重用于 nanosleep 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52231783/

相关文章:

c++ - 如何知道 QStyle 中的标题文本宽度?

c++ - C++ 中的二进制文件,更改音频文件中原始数据的内容

c - 程序将计算大多数提供的值,除了一些

c - 这个程序最后是怎么得到5的呢?

java - 让线程 hibernate 直到设定的日期?

c++ - boost::this_thread::sleep() 与 nanosleep()?

c++ - CUDA 缩减,大阵列的方法

c++ - 使用 std::map 时出错

c - “b++”的汇编

java - 如何调用一个方法,直到它每 x 分钟返回 true