12.07.2015 Views

Hilos - Universidad Nacional de San Antonio Abad del Cusco

Hilos - Universidad Nacional de San Antonio Abad del Cusco

Hilos - Universidad Nacional de San Antonio Abad del Cusco

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

UNIVERSIDAD NACIONAL DE SAN ANTONIO ABAD DEL CUSCOSISTEMAS DE OPERACIONES IGUIA DE LABORATORIOecp 1 <strong>de</strong> 8TEMA: GESTION DE HILOS1) OBJETIVO DE LA PRACTICAa) Capacitar al alumno en la creación y gestión <strong>de</strong> hilos en Linux.b) Capacitar al alumno en la creación <strong>de</strong> aplicaciones que utilicen hilos2) TRABAJO PREPARATORIO.a) Compren<strong>de</strong>r el concepto <strong>de</strong> procesos e hilos.b) Desarrollar la guía previa3) MARCO TEORICOSERVICIOS POSIX PARA LA GESTION DE HILOSATRIBUTOS DE UN HILOCrear atributos <strong>de</strong> un proceso ligeroEste servicio permite iniciar un objeto atributo que se pue<strong>de</strong> utilizar para crear nuevos hilos.El prototipo <strong>de</strong> esta función es:int pthread_attr_init ( pthread_attr_t *attr );Destruir atributosDestruye el objeto <strong>de</strong> tipo atributo pasado como argumento a la misma. Su prototipo es:int pthread_attr_<strong>de</strong>stroy ( pthread_attr_t * attr );Asignar el tamaño <strong>de</strong> la pilaEl prototipo <strong>de</strong> esta función es:int pthread_attr_setstacksize ();pthread_attr_t *attr,int stacksizeObtener el tamaño <strong>de</strong> la pilaEl prototipo <strong>de</strong> esta función es:int pthread_attr_getstacksize ();pthread_attr_t *attr,int stacksize


UNIVERSIDAD NACIONAL DE SAN ANTONIO ABAD DEL CUSCOSISTEMAS DE OPERACIONES IGUIA DE LABORATORIOecp 2 <strong>de</strong> 8Establecer el estado <strong>de</strong> terminaciónEl prototipo <strong>de</strong> esta función es:int pthread_attr_set<strong>de</strong>tachstate ();pthread_attr_t *attr,int <strong>de</strong>tachstateObtener el estado <strong>de</strong> terminaciónEl prototipo <strong>de</strong> esta función es:int pthread_attr_get<strong>de</strong>tachstate ();pthread_attr_t *attr,int *<strong>de</strong>tachstateCREACION, IDENTIFICACION Y TERMINACION DE HILOS.Crear un hiloEl prototipo <strong>de</strong> esta función es el siguiente:int pthread_create ();pthread_t *thread,pthread_attr_r *attr,void*(*start_routine) (void*),void *argObtener el i<strong>de</strong>ntificador <strong>de</strong> un hiloEl prototipo <strong>de</strong> esta función es:pthread_t pthread_self ( void );Esperar la terminación <strong>de</strong> un hiloEl prototipo <strong>de</strong> esta función es:int pthread_join ();pthread thid,void **valueFinalizar la ejecución <strong>de</strong> un hiloEl prototipo <strong>de</strong> esta función es:int pthread_exit ( void *value );


UNIVERSIDAD NACIONAL DE SAN ANTONIO ABAD DEL CUSCOSISTEMAS DE OPERACIONES IGUIA DE LABORATORIOecp 3 <strong>de</strong> 8COMPILAR UN PROGRAMA QUE UTILIZA HILOS.Para compilar un programa que utiliza hilos, <strong>de</strong>beos utilizar el modificador –lpthread <strong>de</strong>l gcc.Así para compilar el programa llamado ejemplo.c que utiliza hilos, la or<strong>de</strong>n <strong>de</strong> compilación<strong>de</strong>berá ser:gcc –o ejemplo ejemplo.c –pthread4) TRABAJO DE LABORATORIO.a) Escriba una aplicación que cree un hilo que imprima un carácter por consolaSolución/**/Nombre : creaHilo.cObjetivo : crea un hilo que imprime el carácter XAutor : Edwin CarrascoFCreacion : 06/12/2007FModificacion :#inclu<strong>de</strong>#inclu<strong>de</strong>void imprime_x(void ){while(1){fputc('X',st<strong>de</strong>rr);}pthread_exit(0);}main(){// Variablespthread_t hilo;int iret;// creamos un hilo que ejecuta el proceso imprime_xiret = pthread_create(&hilo, NULL,(void*) imprime_x, NULL);// Este proceso imprime el caracter '0'while(1){fputc('O',st<strong>de</strong>rr);}}exit(0);


UNIVERSIDAD NACIONAL DE SAN ANTONIO ABAD DEL CUSCOSISTEMAS DE OPERACIONES IGUIA DE LABORATORIOecp 4 <strong>de</strong> 8b) Escriba un programa que cree dos hilos no in<strong>de</strong>pendientes.Solución/**/Nombre : hilosDependientes.cObjetivo : crea dos hilos <strong>de</strong>pendientesAutor : Edwin CarrascoFCreacion : 06/12/2007FModificacion :#inclu<strong>de</strong>#inclu<strong>de</strong>void func(void){printf( "Soy el hilo %d \n", pthread_self());pthread_exit(0);}main(){pthread_t h1, h2;int iret1, iret2;iret1 = pthread_create(&h1, NULL,(void*) func, NULL);iret2 = pthread_create(&h2, NULL, (void*)func, NULL);printf("El hilo principal %d continua ejecutando\n",getpid());pthread_join(h1, NULL);pthread_join(h2, NULL);}exit(0);c) Escriba un programa que cree dos hilos, a los cuales les <strong>de</strong>be pasar como parámetros elcarácter que cada uno <strong>de</strong>be imprimir, así como el numero <strong>de</strong> veces que imprimirán elmismoSolución/**/Nombre : pasoParametros.cObjetivo : muestra el mecanismo <strong>de</strong> paso <strong>de</strong> parámetros ahilosAutor : Edwin CarrascoFCreacion : 06/12/2007FModificacion :#inclu<strong>de</strong> #inclu<strong>de</strong>


UNIVERSIDAD NACIONAL DE SAN ANTONIO ABAD DEL CUSCOSISTEMAS DE OPERACIONES IGUIA DE LABORATORIOecp 5 <strong>de</strong> 8/* Parametros para funcion <strong>de</strong> impresion. */struct char_print_parms{char caracter; /* El caracter a imprimir. */int cuenta; /* El numero <strong>de</strong> veces a imprimir. */};/* Imprime un numero <strong>de</strong> caracteres en st<strong>de</strong>rr, segun se especifica enPARAMETROS, que es un apuntador a la estructura char_print_parms. */void* char_print (void* parametros){/* Hace un cast sobre el apuntador al tipo a<strong>de</strong>cuado. */struct char_print_parms* p = (struct char_print_parms*) parametros;int i;}for (i = 0; i < p->cuenta; ++i){fputc (p->caracter, st<strong>de</strong>rr);}return NULL;/* El programa main. */int main (){pthread_t hilo1_id;pthread_t hilo2_id;struct char_print_parms hilo1_args;struct char_print_parms hilo2_args;/* Crea un nuevo hilo para imprimir 30,000 'X's. */hilo1_args.caracter = 'X';hilo1_args.cuenta = 30000;pthread_create (&hilo1_id, NULL, &char_print, &hilo1_args);/* Crea un nuevo hilo para imprimir 20,000 'O's. */hilo2_args.caracter = 'O';hilo2_args.cuenta = 20000;pthread_create (&hilo2_id, NULL, &char_print, &hilo2_args);/* Nos aseguramos que elprimer hilo haya terminado */pthread_join(hilo1_id, NULL);/* Nos aseguramos que el segundo hilo haya terminado */pthread_join(hilo2_id, NULL);}/* Po<strong>de</strong>mos salir <strong>de</strong> forma segura */return 0;d) Escriba un programa que cree un hilo. El hilo <strong>de</strong>be <strong>de</strong>volver el N – ésimo número primo.Este valor será, mostrado por el proceso principal


UNIVERSIDAD NACIONAL DE SAN ANTONIO ABAD DEL CUSCOSISTEMAS DE OPERACIONES IGUIA DE LABORATORIOecp 6 <strong>de</strong> 8Solución/**/Nombre : primo.cObjetivo : calcula el N-esimo número primoAutor : Edwin CarrascoFCreacion : 06/12/2007FModificacion :#inclu<strong>de</strong> #inclu<strong>de</strong> /* Calcula numeros primos sucesivos. Devuelve el N-esimo numero primo,en don<strong>de</strong> N es el valor apuntado por *arg. */void* calcula_primo (void* arg){int candidato = 2;int n = *((int*) arg);while (true){int factor;int es_primo = 1;/* Prueba la primalidad mediante divisiones sucesivas. */for (factor = 2; factor < candidato; ++factor){if (candidato % factor == 0){es_primo = 0;break;}}}/* Es el numero primo que estamos buscando? */if (es_primo){if (--n == 0){/* Devuelve el numero primo <strong>de</strong>seado como el valor <strong>de</strong>retorno <strong>de</strong>l hilo. */return (void*) candidato;}}++candidato;}return NULL;int main (){pthread_t hilo;int que_primo = 5000;int primo;


UNIVERSIDAD NACIONAL DE SAN ANTONIO ABAD DEL CUSCOSISTEMAS DE OPERACIONES IGUIA DE LABORATORIOecp 7 <strong>de</strong> 8/* Inicia el hilo procesador, hasta el 5,000-esimo numero primo.*/pthread_create (&hilo, NULL, &calcula_primo, &que_primo);/* Hacer algun otro trabajo aqui... */printf("Estoy esperando\n");/* Esperar que termine el hilo <strong>de</strong> numeros primos, y tomar elresultado.*/pthread_join (hilo, (void*) &primo);/* Imprimir el primo mayor calculado. */printf("El %d-esimo numero primo es %d.\n", que_primo, primo);}return 0;5) PRACTICAS DE LABORATORIOa) Escriba un programa que or<strong>de</strong>ne un arreglo <strong>de</strong> caracteres utilizando el algoritmo Mergeutilizando hilos para cada partición <strong>de</strong>l arreglo. El algoritmo <strong>de</strong> ilustra en el siguientegráfico tomado <strong>de</strong> www.wikipedia.orgb) Implementar una aplicación productor/consumidor utilizando procesos.c) Implementar una aplicación productor/consumidor utilizando hilos.


UNIVERSIDAD NACIONAL DE SAN ANTONIO ABAD DEL CUSCOSISTEMAS DE OPERACIONES IGUIA DE LABORATORIOecp 8 <strong>de</strong> 86) BIBLIOGRAFIAa) www.wikipedia.orgb) http://www.llnl.gov/computing/tutorials/pthreads/c) http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.htmld) http://www.humanfactor.com/pthreads/e) http://sourceware.org/pthreads-win32/f) http://users.actcom.co.il/~choo/lupg/tutorials/multi-thread/multi-thread.htmlg) http://www.ibm.com/<strong>de</strong>veloperworks/linux/library/l-posix1.htmlh) http://pages.cs.wisc.edu/~lhl/cs740/assignments/references/pthreads.psi) http://www.dmoz.org/Computers/Programming/Threads/POSIX/

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!