2
我想在C中實現一個定時器,在一個特定的時間後調用一個函數。我想用線程分別實現定時器。我觀察到,定時器在線程中執行時以兩倍的速度運行,而不是在主函數中執行定時器。clock()(time.h)函數在C中執行定時器的速度是線程中執行速度的兩倍
爲什麼會發生這種情況?我該如何解決它?
代碼1(不帶螺紋):
int main(){
unsigned int x_hours=0;
unsigned int x_minutes=0;
unsigned int x_seconds=0;
unsigned int x_milliseconds=0;
unsigned int totaltime=0,count_down_time_in_secs=0,time_left=0, prev_time =10;
clock_t x_startTime,x_countTime;
count_down_time_in_secs=20;
x_startTime=clock(); // start clock
time_left=count_down_time_in_secs-x_seconds;
while (time_left>0)
{
x_countTime=clock(); // update timer difference
x_milliseconds=x_countTime-x_startTime;
x_seconds=(x_milliseconds/(CLOCKS_PER_SEC))-(x_minutes*60);
x_minutes=(x_milliseconds/(CLOCKS_PER_SEC))/60;
x_hours=x_minutes/60;
time_left=count_down_time_in_secs-x_seconds; // subtract to get difference
if(time_left-prev_time != 0)
{
//printf("\nx_countTime = %ju\n",x_countTime);
prev_time = time_left;
//printf("\nYou have %d seconds left (%d) count down timer by TopCoder",time_left,count_down_time_in_secs);
}
}
printf("\n\n\nTime's out\n\n\n");
return 0;
}
代碼2(帶定時器),因爲時間由兩個調用測量clock
措施在不同平臺上不同的東西
void *timerThread(void *param){
unsigned int x_hours=0;
unsigned int x_minutes=0;
unsigned int x_seconds=0;
unsigned int x_milliseconds=0;
unsigned int totaltime=0,count_down_time_in_secs=0,time_left=0,prev_time =10;
clock_t x_startTime,x_countTime;
count_down_time_in_secs=20;
x_startTime=clock(); // start clock
time_left=count_down_time_in_secs-x_seconds;
while (time_left>0)
{
x_countTime=clock(); // update timer difference
x_milliseconds=x_countTime-x_startTime;
x_seconds=(x_milliseconds/(CLOCKS_PER_SEC))-(x_minutes*60);
x_minutes=(x_milliseconds/(CLOCKS_PER_SEC))/60;
x_hours=x_minutes/60;
time_left=count_down_time_in_secs-x_seconds; // subtract to get difference
if(time_left-prev_time != 0)
{
printf("\nx_countTime = %ju\n",x_countTime);
prev_time = time_left;
printf("\nYou have %d seconds left (%d) count down timer by TopCoder",time_left,count_down_time_in_secs);
}
}
printf("\n\n\nTime's out\n\n\n");
exit(1);
}
int main()
{
pthread_t *thread_id;
pthread_create(&thread_id, NULL, timerThread, NULL);
while(1);
}
謝謝。是的,我使用的是Unix系統。 –