I need to use some timers in my code. I've got something like this:
struct sigevent ec;
ec.sigev_notify = SIGEV_THREAD;
ec.sigev_value.sival_ptr = &c_timer;
ec.sigev_notify_function = c_thread;
ec.sigev_notify_attributes = NULL;
secs = floor(c);
nsecs = (long long) SECOND * (c - secs);
printf("%ds\t%lldns\n\n",secs,nsecs);
it1c.it_value.tv_sec = secs;
it1c.it_value.tv_nsec = nsecs;
it1c.it_interval.tv_sec = 0;
it1c.it_interval.tv_nsec = 0;
timer_create(CLOCK_PROCESS_CPUTIME_ID, &ec, &c_timer);
timer_settime(c_timer, 0, &it1c, NULL);
Where c_thread is some simple function which is setting new timer, SECOND is:
#define SECOND 1000000000
c is something like 2.25
And my problem is that this timer doesn't call c_thread when it should. When i change CLOCK_PROCESS_CPUTIME_ID to CLOCK_REALTIME everything is ok, and it is called, but when I am using first one nothing happens. I am also checking CLOCK_PROCESS_CPUTIME_ID using other CLOCK_REALTIME timer with clock_gettime function and values of clock reach my it_value.
Any ideas what could be wrong?
And my second question: Is there any way to pass some arguments to function called as thread using timers?
#annamataris problem was not related to spinlock and nanosleep stuff. There is reason to use only CLOCK_REALTIME because.
The POSIX timers system calls first appeared in Linux 2.6. Prior to
this, glibc provided an incomplete user-space implementation
(CLOCK_REALTIME timers only) using POSIX threads, and in glibc
versions before 2.17, the implementation falls back to this technique
on systems running pre-2.6 Linux kernels.
Read man timer_create for more info.
Related
Given the following code, the expectation is for there to be a one-second sleep each time select() is called. However, the sleep only occurs on the first call and all subsequent calls result in no delay:
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
for (;;)
{
/* Sleep for one second */
int result=select(0, NULL, NULL, NULL, &tv);
printf("select returned: %d\n",result);
}
}
Why do all calls to select() except the first return immediately?
Compiler: gcc 4.9.2
OS: Centos 7 (Linux)
Kernel info: 3.10.0-327.36.3.el7.x86_64
From the man page:
On Linux, select() modifies timeout to reflect the amount of time not
slept
So, set tv [in the loop] before calling select
As stated in the manpage
On Linux, select() modifies timeout to reflect the amount of time not
slept; most other implementations do not do this. (POSIX.1 permits
either behavior.) This causes problems both when Linux code which
reads timeout is ported to other operating systems, and when code is
ported to Linux that reuses a struct timeval for multiple select()s
in a loop without reinitializing it. Consider timeout to be unde‐
fined after select() returns.
As the first run ended by timeout, the tv value is reset to 0 seconds. Solution: reinitialize tv on every run.
I have a function and that is called at specific intervals. I need to check the time previously its called, and the current time. If the difference between the function call is 10 milliseconds then execute some piece of code. Sleep should not be used since some other things are executing in parallel. I have written the following code and the function is called at every 10 milliseconds but the difference i am calcuting is giving 1 or 2 milliseconds less sometimes. what is best way to calculate the difference?
fxn()
{
int logCurTime;
static int logPrevTime = 0, logDiffTime = 0;
getCurrentTimeInMilliSec(&logCurTime);
if (logPrevTime > 0)
logDiffTime += logCurTime - logPrevTime;
if (logCurTime <= logPrevTime)
return;
if (logDiffTime >= 10)
{
...
...
logDiffTime = 0;
}
logPrevTime = logCurTime;
}
For eg:
fxn is called 10 times with the interval of 10 milliseconds. some instance logDiffTime is just 8 or 9 and next instance it accounts the remaining time. i.e., 11 or 12.
Using sleep() to get code executed in specific time intervals is indeed a bad idea. Register your function as the handler for a timer interrupt. Then it will be called very precisely on time.
If you're doing heavy lifting stuff in your function, than you should do it in another thread, because you will run into trouble when you're function is taking too long. (it will just be called from the beginning again).
In posix (linux) you could do it like this
#include <sys/time.h>
#include <stdio.h>
#include <signal.h>
if (signal (SIGALRM, fxn) == SIG_ERR)
perror ("Setting your function as timer handler failed");
unsigned seconds = 42;//your time
struct itimerval old, new_time;
new_time.it_interval.tv_usec = 0;
new_time.it_interval.tv_sec = 0;
new_time.it_value.tv_usec = 0;
new_time.it_value.tv_sec = (long int) seconds;
if (setitimer (ITIMER_REAL, &new_time, &old) != 0)
perror ("Setting the timer failed");
or in windows:
#include <Windows.h>
void Fxn_Timer_Proc_Wrapper(HWND,UINT,UINT_PTR,DWORD){
fxn();
}
unsigned seconds = 42;//your time
UINT_PTR timer_id;
if ( (timer_id = SetTimer(NULL,NULL,seconds *1000,(TIMERPROC) Fxn_Timer_Proc_Wrapper) == NULL){
//failed to create a timer
}
It may not be exactly what you are looking for, however I feel it should be clarified:
The sleep call only suspends the calling thread, not all threads of the process. Thus, you can still run parallel threads while one of them sleeps.
See this question for more:
Do sleep functions sleep all threads or just the one who call it?
For a solution to your problem you should register your function with a timer interrupt. See the other answer on how to do that.
10ms is at the edge of what is achievable see stack overflow : 1ms timer . However, several suggestions on how to get 10ms did come out.
timerfd_create allows your program to wait using select.
timer_settime allows your program to request the 10ms interval.
The caveats on linux are :-
May not be scheduled - the OS could be busy doing something else.
May not be accurate - as 10ms appears to be the shortest interval that works, it may be +/- 1 or 2 ms.
I'm building a multithreaded application with pthreads and need a thread to periodically check some stuff. During the time in between this thread shouldn't use any CPU. Is this possible with usleep()? Is usleep() not busy waiting? Or is there a better solution?
The function usleep has been removed from SUSv4. You should probably use nanosleep instead or timers (setitimer, etc).
As R.. notes in the comments, should the sleep be implemented as a busy wait:
The thread would continue to use the CPU
Other (lower-priority) threads wouldn't get a chance to run
Thus:
Some might use signals (I think SUSv3 mentioned SIGALARM?)
Some might use fancy timers
(usleep is not part of the C standard, but of an ancient POSIX standard. But see below.)
No, the POSIX specification of usleep clearly states
The usleep() function will cause the calling thread to be suspended
from execution ...
so this clearly requires that it suspends execution and lets the resources to other processes or threads.
As already be mentioned by others, the POSIX function nanosleep is now replacing usleep and you should use that. C (since C11) has a function thrd_sleep that is modeled after nanosleep.
Just be aware that both usleep() and nanosleep() can be interrupted by a signal. nanosleep() lets you pass in an extra timespec pointer where the remaining time will be stored if that happens. So if you really need to guarantee your delay times, you'll probably want to write a simple wrapper around nanosleep().
Beware that this is not tested, but something along these lines:
int myNanoSleep(time_t sec, long nanosec)
{
/* Setup timespec */
struct timespec req;
req.tv_sec = sec;
req.tv_nsec = nanosec;
/* Loop until we've slept long enough */
do
{
/* Store remainder back on top of the original required time */
if( 0 != nanosleep( &req, &req ) )
{
/* If any error other than a signal interrupt occurs, return an error */
if(errno != EINTR)
return -1;
}
else
{
/* nanosleep succeeded, so exit the loop */
break;
}
} while( req.tv_sec > 0 || req.tv_nsec > 0 )
return 0; /* Return success */
}
And if you ever need to wake the thread for something other than a periodic timeout, take a look at condition variables and pthread_cond_timedwait().
On Linux, it is implemented with the nanosleep system call which is not a busy wait.
Using strace, I can see that a call to usleep(1) is translated into nanosleep({0, 1000}, NULL).
usleep() is a C runtime library function built upon system timers.
nanosleep() is a system call.
Only MS-DOS, and like ilk, implement the sleep functions as busy waits. Any actual operating system which offers multitasking can easily provide a sleep function as a simple extension of mechanisms for coordinating tasks and processes.
I don't know exactly how to word a search for this.. so I haven't had any luck finding anything.. :S
I need to implement a time delay in C.
for example I want to do some stuff, then wait say 1 minute, then continue on doing stuff.
Did that make sense? Can anyone help me out?
In standard C (C99), you can use time() to do this, something like:
#include <time.h>
:
void waitFor (unsigned int secs) {
unsigned int retTime = time(0) + secs; // Get finishing time.
while (time(0) < retTime); // Loop until it arrives.
}
By the way, this assumes time() returns a 1-second resolution value. I don't think that's mandated by the standard so you may have to adjust for it.
In order to clarify, this is the only way I'm aware of to do this with ISO C99 (and the question is tagged with nothing more than "C" which usually means portable solutions are desirable although, of course, vendor-specific solutions may still be given).
By all means, if you're on a platform that provides a more efficient way, use it. As several comments have indicated, there may be specific problems with a tight loop like this, with regard to CPU usage and battery life.
Any decent time-slicing OS would be able to drop the dynamic priority of a task that continuously uses its full time slice but the battery power may be more problematic.
However C specifies nothing about the OS details in a hosted environment, and this answer is for ISO C and ISO C alone (so no use of sleep, select, Win32 API calls or anything like that).
And keep in mind that POSIX sleep can be interrupted by signals. If you are going to go down that path, you need to do something like:
int finishing = 0; // set finishing in signal handler
// if you want to really stop.
void sleepWrapper (unsigned int secs) {
unsigned int left = secs;
while ((left > 0) && (!finishing)) // Don't continue if signal has
left = sleep (left); // indicated exit needed.
}
Here is how you can do it on most desktop systems:
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
void wait( int seconds )
{ // Pretty crossplatform, both ALL POSIX compliant systems AND Windows
#ifdef _WIN32
Sleep( 1000 * seconds );
#else
sleep( seconds );
#endif
}
int
main( int argc, char **argv)
{
int running = 3;
while( running )
{ // do something
--running;
wait( 3 );
}
return 0; // OK
}
Here is how you can do it on a microcomputer / processor w/o timer:
int wait_loop0 = 10000;
int wait_loop1 = 6000;
// for microprocessor without timer, if it has a timer refer to vendor documentation and use it instead.
void
wait( int seconds )
{ // this function needs to be finetuned for the specific microprocessor
int i, j, k;
for(i = 0; i < seconds; i++)
{
for(j = 0; j < wait_loop0; j++)
{
for(k = 0; k < wait_loop1; k++)
{ // waste function, volatile makes sure it is not being optimized out by compiler
int volatile t = 120 * j * i + k;
t = t + 5;
}
}
}
}
int
main( int argc, char **argv)
{
int running = 3;
while( running )
{ // do something
--running;
wait( 3 );
}
return 0; // OK
}
The waitloop variables must be fine tuned, those did work pretty close for my computer, but the frequency scale thing makes it very imprecise for a modern desktop system; So don't use there unless you're bare to the metal and not doing such stuff.
Check sleep(3) man page or MSDN for Sleep
Although many implementations have the time function return the current time in seconds, there is no guarantee that every implementation will do so (e.g. some may return milliseconds rather than seconds). As such, a more portable solution is to use the difftime function.
difftime is guaranteed by the C standard to return the difference in time in seconds between two time_t values. As such we can write a portable time delay function which will run on all compliant implementations of the C standard.
#include <time.h>
void delay(double dly){
/* save start time */
const time_t start = time(NULL);
time_t current;
do{
/* get current time */
time(¤t);
/* break loop when the requested number of seconds have elapsed */
}while(difftime(current, start) < dly);
}
One caveat with the time and difftime functions is that the C standard never specifies a granularity. Most implementations have a granularity of one second. While this is all right for delays lasting several seconds, our delay function may wait too long for delays lasting under one second.
There is a portable standard C alternative: the clock function.
The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC.
The clock function solution is quite similar to our time function solution:
#include <time.h>
void delay(double dly){
/* save start clock tick */
const clock_t start = clock();
clock_t current;
do{
/* get current clock tick */
current = clock();
/* break loop when the requested number of seconds have elapsed */
}while((double)(current-start)/CLOCKS_PER_SEC < dly);
}
There is a caveat in this case similar to that of time and difftime: the granularity of the clock function is left to the implementation. For example, machines with 32-bit values for clock_t with a resolution in microseconds may end up wrapping the value returned by clock after 2147 seconds (about 36 minutes).
As such, consider using the time and difftime implementation of the delay function for delays lasting at least one second, and the clock implementation for delays lasting under one second.
A final word of caution: clock returns processor time rather than calendar time; clock may not correspond with the actual elapsed time (e.g. if the process sleeps).
For delays as large as one minute, sleep() is a nice choice.
If someday, you want to pause on delays smaller than one second, you may want to consider poll() with a timeout.
Both are POSIX.
There are no sleep() functions in the pre-C11 C Standard Library, but POSIX does provide a few options.
The POSIX function sleep() (unistd.h) takes an unsigned int argument for the number of seconds desired to sleep. Although this is not a Standard Library function, it is widely available, and glibc appears to support it even when compiling with stricter settings like --std=c11.
The POSIX function nanosleep() (time.h) takes two pointers to timespec structures as arguments, and provides finer control over the sleep duration. The first argument specifies the delay duration. If the second argument is not a null pointer, it holds the time remaining if the call is interrupted by a signal handler.
Programs that use the nanosleep() function may need to include a feature test macro in order to compile. The following code sample will not compile on my linux system without a feature test macro when I use a typical compiler invocation of gcc -std=c11 -Wall -Wextra -Wpedantic.
POSIX once had a usleep() function (unistd.h) that took a useconds_t argument to specify sleep duration in microseconds. This function also required a feature test macro when used with strict compiler settings. Alas, usleep() was made obsolete with POSIX.1-2001 and should no longer be used. It is recommended that nanosleep() be used now instead of usleep().
#define _POSIX_C_SOURCE 199309L // feature test macro for nanosleep()
#include <stdio.h>
#include <unistd.h> // for sleep()
#include <time.h> // for nanosleep()
int main(void)
{
// use unsigned sleep(unsigned seconds)
puts("Wait 5 sec...");
sleep(5);
// use int nanosleep(const struct timespec *req, struct timespec *rem);
puts("Wait 2.5 sec...");
struct timespec ts = { .tv_sec = 2, // seconds to wait
.tv_nsec = 5e8 }; // additional nanoseconds
nanosleep(&ts, NULL);
puts("Bye");
return 0;
}
Addendum:
C11 does have the header threads.h providing thrd_sleep(), which works identically to nanosleep(). GCC did not support threads.h until 2018, with the release of glibc 2.28. It has been difficult in general to find implementations with support for threads.h (Clang did not support it for a long time, but I'm not sure about the current state of affairs there). You will have to use this option with care.
Try sleep(int number_of_seconds)
sleep(int) works as a good delay. For a minute:
//Doing some stuff...
sleep(60); //Freeze for A minute
//Continue doing stuff...
Is it timer?
For WIN32 try http://msdn.microsoft.com/en-us/library/ms687012%28VS.85%29.aspx
you can simply call delay() function. So if you want to delay the process in 3 seconds, call delay(3000)...
If you are certain you want to wait and never get interrupted then use sleep in POSIX or Sleep in Windows. In POSIX sleep takes time in seconds so if you want the time to be shorter there are varieties like usleep() which uses microseconds. Sleep in Windows takes milliseconds, it is rare you need finer granularity than that.
It may be that you wish to wait a period of time but want to allow interrupts, maybe in the case of an emergency. sleep can be interrupted by signals but there is a better way of doing it in this case.
Therefore I actually found in practice what you do is wait for an event or a condition variable with a timeout.
In Windows your call is WaitForSingleObject. In POSIX it is pthread_cond_timedwait.
In Windows you can also use WaitForSingleObjectEx and then you can actually "interrupt" your thread with any queued task by calling QueueUserAPC. WaitForSingleObject(Ex) will return a code determining why it exited, so you will know when it returns a "TIMEDOUT" status that it did indeed timeout. You set the Event it is waiting for when you want it to terminate.
With pthread_cond_timedwait you can signal broadcast the condition variable. (If several threads are waiting on the same one, you will need to broadcast to wake them all up). Each time it loops it should check the condition. Your thread can get the current time and see if it has passed or it can look to see if some condition has been met to determine what to do. If you have some kind of queue you can check it. (Your thread will automatically have a mutex locked that it used to wait on the condition variable, so when it checks the condition it has sole access to it).
// Provides ANSI C method of delaying x milliseconds
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void delayMillis(unsigned long ms) {
clock_t start_ticks = clock();
unsigned long millis_ticks = CLOCKS_PER_SEC/1000;
while (clock()-start_ticks < ms*millis_ticks) {
}
}
/*
* Example output:
*
* CLOCKS_PER_SEC:[1000000]
*
* Test Delay of 800 ms....
*
* start[2054], end[802058],
* elapsedSec:[0.802058]
*/
int testDelayMillis() {
printf("CLOCKS_PER_SEC:[%lu]\n\n", CLOCKS_PER_SEC);
clock_t start_t, end_t;
start_t = clock();
printf("Test Delay of 800 ms....\n", CLOCKS_PER_SEC);
delayMillis(800);
end_t = clock();
double elapsedSec = end_t/(double)CLOCKS_PER_SEC;
printf("\nstart[%lu], end[%lu], \nelapsedSec:[%f]\n", start_t, end_t, elapsedSec);
}
int main() {
testDelayMillis();
}
C11 has a function specifically for this:
#include <threads.h>
#include <time.h>
#include <stdio.h>
void sleep(time_t seconds) {
struct timespec time;
time.tv_sec = seconds;
time.tv_nsec = 0;
while (thrd_sleep(&time, &time)) {}
}
int main() {
puts("Sleeping for 5 seconds...");
sleep(5);
puts("Done!");
return 0;
}
Note that this is only available starting in glibc 2.28.
for C use in gcc.
#include <windows.h>
then use Sleep(); /// Sleep() with capital S. not sleep() with s .
//Sleep(1000) is 1 sec /// maybe.
clang supports sleep(), sleep(1) is for 1 sec time delay/wait.
For short delays (say, some microseconds) on Linux OS, you can use "usleep":
// C Program to perform short delays
#include <unistd.h>
#include <stdio.h>
int main(){
printf("Hello!\n");
usleep(1000000); // For a 1-second delay
printf("Bye!\n);
return 0;
system("timeout /t 60"); // waits 60s. this is only for windows vista,7,8
system("ping -n 60 127.0.0.1 >nul"); // waits 60s. for all windows
Write this code :
void delay(int x)
{ int i=0,j=0;
for(i=0;i<x;i++){for(j=0;j<200000;j++){}}
}
int main()
{
int i,num;
while(1) {
delay(500);
printf("Host name");
printf("\n");}
}
I'm using select() on a Linux/ARM platform to see if a udp socket has received a packet. I'd like to know how much time was remaining in the select call if it returns before the timeout (having detected a packet).
Something along the lines of:
int wait_fd(int fd, int msec)
{
struct timeval tv;
fd_set rws;
tv.tv_sec = msec / 1000ul;
tv.tv_usec = (msec % 1000ul) * 1000ul;
FD_ZERO( & rws);
FD_SET(fd, & rws);
(void)select(fd + 1, & rws, NULL, NULL, & tv);
if (FD_ISSET(fd, &rws)) { /* There is data */
msec = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
return(msec?msec:1);
} else { /* There is no data */
return(0);
}
}
The safest thing is to ignore the ambiguous definition of select() and time it yourself.
Just get the time before and after the select and subtract that from the interval you wanted.
If I recall correctly, the select() function treats the timeout and an I/O parameter and when select returns the time remaining is returned in the timeout variable.
Otherwise, you will have to record the current time before calling, and again after and obtain the difference between the two.
From "man select" on OSX:
Timeout is not changed by select(), and may be reused on subsequent calls, however it
is good style to re-ini-tialize it before each invocation of select().
You'll need to call gettimeofday before calling select, and then gettimeofday on exit.
[Edit] It seems that linux is slightly different:
(ii) The select function may update the timeout parameter to indicate
how much time was left. The pselect function does not change
this parameter.
On Linux, the function select modifies timeout to reflect the amount of
time not slept; most other implementations do not do this. This causes
problems both when Linux code which reads timeout is ported to other
operating systems, and when code is ported to Linux that reuses a
struct timeval for multiple selects in a loop without reinitializing
it. Consider timeout to be undefined after select returns.
Linux select() updates the timeout argument to reflect the time that has past.
Note that this is not portable across other systems (hence the warning in the OS X manual quoted above) but does work with Linux.
Gilad
Do not use select, try with fd larger than 1024 with your code and see what you will get.