可以将 struct timespec 重用于 nanosleep 吗?

Can struct timespec reusable for nanosleep?

我的程序计划循环以从队列中获取一些元素,但是,继续循环可能会增加 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-ness 意味着它也没有更改它,因此重用它不会有任何坏处。 (以上内容不适用于 rem,因为它已写入,但您没有使用它,所以您不必担心它。)