tags:

views:

130

answers:

2

Is there a way to put a thread to sleep for many days with a resolution of microseconds? usleep can only put the thread to sleep for 1000000 and sleep works in second steps. Is there a way to, may be, use both sleep and usleep to achieve this?

+3  A: 

While it is not yet time to wake up:

  • Check the current time
  • Go to sleep a bit shorter than when you want to wake up.

This way, you can periodically check the time, increasingly faster and more detailed as you reach the time you want to wake up.

Sjoerd
What if I am waiting for a signal to wake my thread up?
lies
@lies If you wait for a signal, why do you need a sleep? Use a message queue
Gianluca
@lies: It usually helps a lot if you post your intended use in the question. There might be better alternatives than *sleeping*, but if you only ask about sleeping then you will not get that information. *'Be careful if you don't know where you are going, because you might not get there'* -- Yogi Berra
David Rodríguez - dribeas
+5  A: 

Just divide the large sleep in several small sleep periods.

int64_t time_to_sleep = ...;
int peroid_to_sleep = ...;
while( time_to_sleep > 0 )
{
     usleep( period_slept );
     time_to_sleep -= period_slept; 
}
Christopher
... and add even more drift to the meassure. If you are going to do this, it would be better to `sleep()` for the integer part of seconds and `usleep()` for the remainder time.
David Rodríguez - dribeas