Oktaheta
Oktaheta

Reputation: 626

Can struct timespec reusable for nanosleep?

My program planning to looping for getting some element from the queue, however, keep looping might overhead CPU usage, I'm wonder to put a nanosleep with 1ms wait. Can I just make struct timespec shared_time_wait; on global, and reuse it?

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();
 }
}

Upvotes: 1

Views: 511

Answers (1)

From man 2 nanosleep:

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

It's perfectly fine to reuse req, since it's declared as const. Since you aren't changing it yourself, and the const-ness of the function means it's not changing it either, no harm can come of reusing it. (The above wouldn't be true for rem, since it is written to, but you're not using that so you don't have to worry about it.)

Upvotes: 1

Related Questions