What is the easiest, most effective way in C on Linux to asynchronously call a function after a certain delay (like JavaScript's setTimeout
) or s开发者_如何学JAVAet a repetitive timer call it periodically (similar to setInterval
)?
Though this question applies to Linux, I hope there is a method that is cross-platform.
The simplest Linux specific solution is to use the alarm
function:
void alarm_handler (int signum)
{
printf ("Five seconds passed!\n");
}
signal (SIGALRM, alarm_handler);
alarm (5);
getitimer
and setitimer
functions can be used to create timers with higher-precisions. (more...).
There are two ways to go about it:
First, as mentioned in another answer, is signals triggered using alarm()
or setitimer()
. Both functions are available in any OS that adheres to POSIX; there's a third function called ualarm()
which was obsoleted in 2008. The down side is that it's unsafe to do anything significant (e.g., I/O or other system calls) in a signal handler, so really all you want to do is maybe set a flag and let something else pick it up.
Second is to use a thread that sleeps for a certain interval and then calls your function. POSIX standardized threads as an extension in the early 1990s, and most modern OSes that support threads support POSIX threads. The pitfall here is that you have to understand the implications of having two execution contexts share the same data space and design your program accordingly or you're going to run into problems that can be a nightmare to debug.
Be aware that alarms and sleeps only promise to do what they do after at least the specified amount of time has elapsed, so you're not guaranteed the kind of accuracy you'd get on a real-time operating system.
精彩评论