任務是每x(例如x = 10)秒執行一個函數(比如Processfunction()
)。以特定間隔執行功能
使用以下代碼,我可以每x秒呼叫Processfunction()
。
問題:如何處理功能需要超過10秒才能完成執行的情況?
一種方法是在調用Processfunction()
之前有一個標誌來指示Processfunction()
結束執行並檢查它。 有沒有更好的方法來做到這一點?
#include <pthread.h>
#include <unistd.h> // for sleep() and usleep()
void *timerthread(void *timer_parms) {
struct itimerspec new_value;
int max_exp, fd;
struct timespec now;
uint64_t exp;
ssize_t s;
struct timer_params *p =(struct timer_params*)timer_parms;
printf("starttimer Start\n");
/* Create a CLOCK_REALTIME absolute timer with initial
expiration and interval as specified in command line */
if (clock_gettime(CLOCK_REALTIME, &now) == -1)
handle_error("clock_gettime");
new_value.it_value.tv_sec = now.tv_sec;
new_value.it_value.tv_nsec = now.tv_nsec + p->tv_nsec;
new_value.it_interval.tv_sec = p->tv_sec;
new_value.it_interval.tv_nsec = p->tv_nsec;
//max_exp = 5; //No of times
fd = timerfd_create(CLOCK_REALTIME , 0);
if (fd == -1)
handle_error("timerfd_create");
if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &new_value, NULL) == -1)
handle_error("timerfd_settime");
printf("timer started\n");
while(1) // keep checking
{
s = read(fd, &exp, sizeof(uint64_t));
if (s != sizeof(uint64_t))
handle_error("read");
Processfunction(); // Say after X seconds call this function
}
return NULL;
}
int main() {
struct timer_params timer_params_obj;
int res;void *thread_result;
timer_params_obj.tv_sec = 10;
//timer_params_obj.tv_nsec = 10000000 ; //10ms
timer_params_obj.tv_nsec = 0 ;
pthread_t pt;
pthread_create(&pt, NULL, timerthread, &timer_params_obj);
// thread is running and will call Processfunction() every 10 sec
}
你不想有兩個'Processfunction()'同時運行嗎?如果執行時間長於通常允許的間隔持續時間,您是否希望延遲調用或跳過調用? – moooeeeep 2013-03-17 18:45:06
是的,我不希望它在同一時間運行。我想跳過/延遲更長的執行時間。 – m4n07 2013-03-19 15:05:06