/* Autor: Agustín J. González * En este programa se explora el tiempo que una hebra está en estado “ready” (o listo) en espera por hacer uso de la CPU (éste es el estado running). El programa corre dos hebras. Una de ellas calcula el tiempo máximo que la hebra estuvo esperando por usar la CPU y la otra muestra ese valor por pantalla. Como idea un Sansano sugiere usar la función gettimeofday en un loop de N iteraciones, con N ingresado como argumento. * La primera hebra calcula el valor máximo de la diferencia entre dos invocaciones a esta función, este máximo debería corresponder al tiempo de la hebra fuera de la CPU. La segunda hebra se limita a esperar por el cambio del valor máximo y lo muestra por pantalla. Idea: Hebra 1: |-|-|-|-|-|-|-|-|-|........................|-|-|-|-|-|-|-|-|-|................ ← running → ← ready → Hebra 2: ^ muestra máximo int gettimeofday(struct timeval *tv, struct timezone tz); /* tz puede ser NULL. struct timeval { time_t tv_sec; suseconds_t tv_usec; }; */ #include #include #include #include #include pthread_mutex_t maxLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t maxChange = PTHREAD_COND_INITIALIZER; int max=0; void * printMax(void * arg) { while (1) { pthread_mutex_lock(&maxLock); pthread_cond_wait(&maxChange, &maxLock); printf("Max time in ready state so far: %i [us]\n",max); pthread_mutex_unlock(&maxLock); } } int main(int argc, char * argv[]) { pthread_t tid; int err, i; struct timeval ti, tf; int time; int N = atoi(argv[1]); err = pthread_create(&tid, NULL, printMax, NULL); if (err != 0){ printf("can't create thread \n"); exit(0); } gettimeofday(&ti, NULL); for (i=N; i>0 ; i--) { gettimeofday(&tf, NULL); time=(tf.tv_sec-ti.tv_sec)*1000000+(tf.tv_usec-ti.tv_usec); if (time > max) { pthread_mutex_lock(&maxLock); max=time; pthread_mutex_unlock(&maxLock); pthread_cond_signal(&maxChange); } ti=tf; } exit(0); }