В моем приложении мне нужно вычислить время выполнения каждого потока [буквально время, которое потребовалось с начала pthread и его завершения выполнения].Прекращение может быть типа 'pthread_exit' или явной отмены.В следующем коде я использовал специальные данные pthread, чтобы сохранить время начала каждого потока, и, следовательно, я мог найти общее время.Ребята, вы думаете, что следующий подход имеет смысл?Если нет, вход действительно ценится !!!В целях тестирования поток отменяет сам себя после некоторого периода сна.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct _pTime
{
time_t stime;
}pTime;
pthread_key_t kstime;
void cancelRoutine (void * arg)
{
pTime etime, *btime;
time (&(etime.stime));
printf (" Inside cancelRoutine ...tid: %l \n", pthread_self());
btime = (pTime *) pthread_getspecific (kstime);
printf ("Time taken : %lf ", difftime (etime.stime, btime->stime));
}
void * tfunction ( void * arg)
{
int waitTime = (int) arg;
printf ("\n Wait Time is %ud ", waitTime);
pTime *start;
start = (pTime *) malloc (sizeof (pTime));
time (&(start->stime));
pthread_setspecific (kstime, start);
pthread_cleanup_push (cancelRoutine, NULL);
printf (" Invoking the thread \n");
/* Doing Certain Work here */
sleep (waitTime);
pthread_cancel ( pthread_self());
sleep(waitTime);
pthread_cleanup_pop (NULL);
}
int main ( int argc, char **argv)
{
pthread_t tid[2];
int toBeSpend=10, i;
pthread_key_create(&kstime, NULL);
for (i=0; i<2; i++)
pthread_create (&tid[i], NULL, tfunction, (void *)(toBeSpend*(i+1)));
sleep (3);
for(i=0; i<2; i++)
pthread_join (tid[i], NULL);
}