Creating a milisecond timeout timer for threads
Hi!
I have a few threads (pthread) that are created at the same time and run simultaneously. Each of them should last for a given amount time and then finish. For example, if thread#1 should last for 5 seconds and thread#2 for 3 seconds, thread#2 should finish 2s before thread#1, but the total amount of time (for both) has to be around 5s. If I use the time() function (time.h), it works but with a resolution of 1s. In order to have a resolution of 1 millisecond, I was using the clock() function but it works completely wrong depending of the number of threads. I would appreciate ANY comments about a accurate millisecond timer to create a timeout (or virtual interruption) for threads. Thanks. |
You can use select() to make it work like a timer with that resolution.
|
or nanosleep()
|
nanosleep() is good but if you give too much time to sleep lets say 2 sec, it may not work because of overflow, so you can use usleep() that takes input in microseconds or if you want to use nanosleep, use it in a loop like if you want to sleep for i milisecond, give value for 1/100 milisecond and then put that statement in a loop.
// sleep for 1 milisecond for (i=0;i<100;i++) //nanosleep for 1/100 miliseconds |
timeval gtod_now_time;//Do a gettimeofday on this when the prog starts
You may also use such a function to query (roughly) millisecond accurate time progress in a thread: unsigned long _my_mmtime(void){ unsigned long result=0; // long vtime=0; #ifdef _WIN32 result=timeGetTime(); return result; #endif #ifdef LINUX_APP timeval gtod_now_time; gettimeofday(>od_now_time,0); result=(gtod_now_time.tv_usec-gtod_start_time.tv_usec)/1000; result+=(gtod_now_time.tv_sec-gtod_start_time.tv_sec)*1000; return result; #endif return 666;//Not a recognized os } Do a nanosleep/usleep in your thread and query the exact time which has evolved after each successing sleep. BTW If you're thinking of a timing inside a thread which is *guaranteed* to be as accurate as 1 millisecond, I believe it will not work, as Linux (nor Windows) is a realtime os, although at least Linux behaves nicely under that respect. But you don't have too much influence on thread scheduling. |
Quote:
Nanosleep() takes a struct as a parameter which has a seperate filed for seconds, just like pselect(). From "man nanosleep": Code:
int nanosleep(const struct timespec *req, struct timespec *rem); Also, you cannot use usleep() together with sleep() or alarm(). And nanosleep can also be used to continue the "sleep" when interrupted. All-in-all, nanosleep() is the best to use. (or select(), or pselect() for that matter, though they're more complex to use). |
All times are GMT -5. The time now is 02:18 PM. |