Hello,
I have decided to use the sample code. However, I will run the start timer in another thread using pthread.
However, when I run the application it doesn't run for 10 seconds as it should. And it doesn't seem to go into the g_start_timer.
The value I always get returned is: 0. Which cannot be correct. Can anyone see any improvement in my code, as I have done something wrong.
many thanks,
Code:
#include <stdio.h>
#include "stopwatch_timer.h"
int main()
{
printf("Start your timers\n");
/* start the time and run for 10 seconds */
start_timer(10);
int i = 0;
/* do some work */
for(i = 0; i < 1000; i++){}
/* Check and display current time */
printf("Curent time: %d\n", current_time());
return 0;
}
Code:
/* stopwatch_timer.c */
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include "stopwatch_timer.h"
/* prototypes */
int* g_start_timer(void *secs);
static clock_t _current_time = 0;
/* create the thread */
void start_timer(int seconds)
{
pthread_t thread_id;
int rc = 0;
rc = pthread_create(&thread_id, NULL, g_start_timer, (void*) seconds);
if(rc)
{
printf("=== Error Creating thread\n");
}
}
/* start the timing in another thread */
int* g_start_timer(void *secs)
{
printf("Starting thread\n");
int seconds = (int) secs;
printf("g_start_timer: %d\n", (int) seconds);
_current_time = clock() + seconds * CLOCKS_PER_SEC;
/* loop until the 10 seconds has reached */
while(clock() < _current_time){}
pthread_exit(NULL);
}
/* get the current time of work */
int current_time()
{
return (int) _current_time / CLOCKS_PER_SEC;
}
Code:
/* stopwatch_timer.h */
void start_timer(int seconds);
int current_time();