newbie: timers..

M

mike79

hi all,

i am implementing a program using threads. I spawn a separate thread
to execute a task every say 10 seconds. How I achieve this 10 second
delay is by using a for/while loop, and incrementing the counter to a
particular value relevant to 10 seconds. As follows:

timerThread()
{
for (i = 0; i < 100000000; i++);
// Next, do the task
}

As this is very resource/processor consuming (spending alot of time
doing nothing), I was wondering if C provided any functions which are
more efficient than this method.

All help or suggestions are welcome, thank you for your help!
mike79
 
K

Keith Thompson

i am implementing a program using threads. I spawn a separate thread
to execute a task every say 10 seconds. How I achieve this 10 second
delay is by using a for/while loop, and incrementing the counter to a
particular value relevant to 10 seconds. As follows:

timerThread()
{
for (i = 0; i < 100000000; i++);
// Next, do the task
}

As this is very resource/processor consuming (spending alot of time
doing nothing), I was wondering if C provided any functions which are
more efficient than this method.

It's also going to behave very differently when you run it on a slower
or faster system. For that matter, any decent optimizing compiler can
replace your loop with a single assignment: "i = 100000000;".

There's no portable method in standard C to sleep for 10 seconds
without gobbling CPU time. If you're using threads, you're already
beyond the realm of portable C, so you might as well look into
OS-specific solutions.

<OFFTOPIC>
Many systems provide a sleep() function that's probably just what
you're looking for. If you need better than one-second resolution,
there are other less portable solutions. If you have more questions
about sleep(), or about threads, you should ask in a newsgroup devoted
to whatever system you're using (after first reading your system's
documentation, of course).
</OFFTOPIC>
 
E

EventHelix.com

This is operating system dependent. You could try sleep for 10 seconds
instead of looping.

Another option would be to raise an event and catch the corresponding
signal using a signal handler (works in Linux and Unix environment).

What operating system are you using?

Sandeep
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top