Hi,
can someone help me to complete my code with a function that can check the result of a timer "check_timer" and another one that reset this timer if it had expired "reset_timer"? THANKS FOR THE HELP.
Code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <sys/time.h>
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
/* call back function - inform the user the time has expired */
void timeout_call_back(pthread_t thread_id)
{
printf("Welcome thread %ld, your time is up ===\n", pthread_self());
// doing some other stuff
}
/* Go to sleep for a period of seconds */
static void* start_timer(void *args)
{
/* function pointer */
void (*finish_function)(pthread_t);
int seconds = *((int*) args);
finish_function = timeout_call_back;
struct timeval now;
struct timespec timeout;
pthread_mutex_lock(&mut);
printf("thread ID : %ld, are waiting for %d seconds to to expire\n", pthread_self(), seconds);
gettimeofday(&now, NULL);
timeout.tv_sec = now.tv_sec + seconds;
timeout.tv_nsec = now.tv_usec * 1000;
pthread_cond_timedwait(&cond, &mut, &timeout);
(*finish_function)(pthread_self());
pthread_mutex_unlock(&mut);
pthread_exit(NULL);
}
int main_threads_launcher()
{
pthread_t thread1, thread2, thread3;
int seconds1 = 5;
int seconds2 = 10;
int seconds3 = 15;
pthread_mutex_t mut_main = PTHREAD_MUTEX_INITIALIZER;
int rc1, rc2, rc3;
rc1 = pthread_create(&thread1, NULL, start_timer, (void *) &seconds1);
if(rc1)
printf("Failed to create thread1\n");
rc2 = pthread_create(&thread2, NULL, start_timer, (void *) &seconds2);
if(rc2)
printf("Failed to create thread2\n");
rc3 = pthread_create(&thread3, NULL, start_timer, (void *) &seconds3);
if(rc3)
printf("Failed to create thread3\n");
// HOW CAN I CHECK FOR TIMERS EXPIRATIONS IN MULTITHREADED ENVIRONNEMENT?
pthread_mutex_lock(&mut_main);
if (check_timer(thread_id) has expired) { // I want to write this function
// I want to reset thread timer
reset_thread_timer(thread_id)
}
else {
// doing some stuff
}
pthread_mutex_unlock(&mut_main);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
printf("End of all threads\n");
return 0;
}
Thanks.