6

I am using multiple threads in my program. I want a specific thread to be waken up after 500ms. How can I do that without using a usleep(500)?

6
  • 1
    usleep is the only sane way to do this. What's your problem with using this? Dec 18, 2015 at 3:38
  • Ok. Thanks. But can we do it based on the system time elapsed or something?
    – paulgked
    Dec 18, 2015 at 3:44
  • 1
    Hope it may useful to you. linux.die.net/man/2/select
    – Punit Vara
    Dec 18, 2015 at 4:46
  • Thanks. gettimeofday() worked.
    – paulgked
    Dec 18, 2015 at 5:25
  • In Windows you would WaitForSingleObject on the "kill me" event that your caller can set to tell your thread to finish. You should use a similar method. Threads that are asleep with no way of terminating them other than asking the kernel to purge the thread object is bad program design.
    – Lundin
    Dec 18, 2015 at 7:54

2 Answers 2

2

The socket API like select can be used as a timer.

struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 500;
select(0, NULL, NULL, NULL, &tv);

You may need this choice.

3
  • Can you show how to use select to "make a thread wake up and suspend for 500ms continuously" per the question?
    – Déjà vu
    Dec 18, 2015 at 5:32
  • @ringø, It is confused what 'make a thread' mean. Maybe the question is about sleep. the thread can sleep itself using select.
    – seamaner
    Dec 18, 2015 at 5:48
  • Sorry for the confuison.
    – paulgked
    Jan 4, 2016 at 9:02
0

clock_nanosleep is the POSIX compliant version to sleep for an interval on a high resolution clock, see man page, for example on http://linux.die.net/man/2/clock_nanosleep for details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.