2017-08-09 94 views
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); 
} 

回答

2

要小心。在Unix和類Unix系統(例如macOS和Linux)上,區別在於進程CPU時間,而在Windows上則基於掛鐘。

至於你的問題我你是在一個Unix或類Unix系統。我認爲這只是因爲兩個clock調用之間的差異是進程已過去的CPU時間,並且如果您使用線程,那麼看起來時間正在加速,因爲(因爲線程並行運行)。這與多線程進程使用超過100%CPU時間的原因相同。

解決方法是使用其他方式來測量時間,這與CPU時間和線程無關。例如clock_gettime

+0

謝謝。是的,我使用的是Unix系統。 –