I want to implement a timer in C, after a particular time a function is to be called. I want to implement the timer separately using a thread. I observed that the timer runs at twice the speed when it is implemented in a thread as opposed to when it is implemented in the main function.
Why does this happen? How can I fix it?
Code 1(without thread):
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;
}
Code 2(with timer)
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);
}