02 - hilos

Upload: rigo-tovar-lazo

Post on 14-Jan-2016

215 views

Category:

Documents


0 download

DESCRIPTION

Hilos para SO

TRANSCRIPT

  • HilosCaptulo 5Silberschatz Galvin

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    HilosConceptoBeneficiosHilos a nivel krnel y a nivel usuarioModelos multihilosHilos de Solaris 2Hilos de Java

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    HilosUn hilo (o proceso ligero) es una unidad bsica de utilizacin del CPU; consiste de:Contador de programaConjunto de registrosEspacio de stack

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    HilosUn hilo comparte con sus hilos pares:Seccin de cdigoSeccin de datosRecursos del sistema operativoEn conjunto se les conoce como tareaUn proceso tradicional o pesado, es igual a una tarea con un hilo.

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Hilos y procesos

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Procesos con un solo hilo y con mltiples hilosHiloHilosMono-hiloMulti-hilo

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Modelos de procesos de un solo hilo y de muchos hilosBloque decontroldel hiloStackdelusuarioStackdelusuarioStackdelkernelStackdelKernelEspacio dedireccionesdel usuarioEspacio dedireccionesdel usuarioBloque decontrol delprocesoBloquede controldel procesoHiloModelo de procesode un solo hiloModelo de procesomultihilosBloque decontroldel hiloStackdelusuarioStackdelkernelHiloBloque decontroldel hiloStackdelusuarioStackdelkernelHilo

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    MultihiloSistema operativo que mantiene varios hilos de ejecucin dentro de un mismo proceso. MS-DOS soporta un solo hilo. UNIX soporta mltiples procesos de usuarios, pero slo un hilo por proceso. Windows 2000, Solaris, Linux, Mac OS, OS/2 soportan mltiples hilos.

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    HilosEn una tarea donde hay mltiples hilos, mientras un hilo servidor est bloqueado y esperando, otro hilo en la misma tarea puede ejecutarse.Cooperacin de mltiples hilos en la misma tarea aumenta la tasa de trabajos por unidad tiempo y mejora el rendimiento.Aplicaciones que requieren compartir un buffer comn (productor-consumidor) sacan provecho de la utilizacin de hilos.

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    HilosLos hilos proveen un mecanismo que permiten a procesos secuenciales hacer llamadas bloqueantes mientras otros en paralelo ejecutan otras operaciones.

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    BeneficiosComparticin de recursosEconomaUtilizacin de arquitecturas de mltiples procesadores

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Hilos a nivel usuarioEl manejo de los hilos lo hace una librera de hilos a nivel usuario

    Ejemplos- Hilos POSIX- Mach C-threads- Hilos de Solaris

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Hilos a nivel usuario (un CPU con dos ncleos)Nivel krnel (sistema operativo)Nivel usuarioProceso de usuario gestiona y planifica los mltiples hilosCoreCoreCPUHardwarePlanificador del SO

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Ventajas de los hilos a nivel usuarioLos hilos podan implementarse en las aplicaciones que se ejecutaban en sistemas operativos que no son capaces de planificar hilosEjemplo: Primeras implementaciones de UNIX

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Desventajas de los hilos a nivel usuarioEl planificador del sistema operativo solo ve un hilo por proceso No ve los hilos a nivel usuarioUsa un solo ncleo del procesador en un procesador que tiene ms de un ncleoNo puede distribuir los hilos a nivel el usuario en los dos ncleos

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Hilos a nivel krnelSoportados por el krnel EjemplosWindows 95/98/NTSolarisLinuxMac OS

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Hilos a nivel kernel (con un CPU con un solo ncleo)Nivel krnel (sistema operativo)Nivel usuarioCoreCPUHardwarePlanificador del SO

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Hilos a nivel kernel (con un CPU con doble ncleo)Nivel krnel (sistema operativo)Nivel usuarioCoreCoreCPUHardwarePlanificador del SO

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Ventajas de los hilos a nivel krnelEl proceso de usuario no se tiene que encargar de la planificacin de los hilos

    Si tenemos un procesador con ms de un ncelo, el Sistema operativo puede planificar los hilos en diferentes ncleos

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Modelos multihilosMuchos a unoUno a unoMuchos a muchos

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Muchos a unoMuchos hilos a nivel usuario mapeados a un hilo a nivel krnel.

    Usado en sistemas que no soportan hilos a nivel krnel.

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Modelo muchos a uno

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Relaciones entre estados de ULTs y estados de procesosEjecucinListoListoEjecucinBloqueadoBloqueadoListoEjecucinBloqueadoHilo 1Hilo 2Proceso BKernelUsuario

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Uno a unoCada hilo a nivel usuario corresponde a un hilo del krnel.

    Ejemplos:- Windows 95/98/NT- OS/2

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Modelo uno a uno

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Modelo muchos a muchos

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Soporte de hilos en Solaris 2Solaris 2 es una versin de UNIX con soporte para hilos a nivel kernel y a nivel usuario, procesamiento simtrico y planificacin en tiempo real.

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Soporte de hilos en Solaris 2LWP Nivel intermedio entre los hilos a nivel kernel y los hilos a nivel usuario.

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Hilos en Solaris 2. Recursos necesarios para los tipos de hilosHilos del kernelEstructura de datos pequea y un stackEl intercambio de hilos no requiere cambiar la informacin del acceso a memoriaCambios de hilos relativamente rpidos

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Hilos en Solaris 2. Recursos necesarios para los tipos de hilosLWPPCB con datos de los registrosInformacin sobre la memoriaEl intercambio entre LWP es relativamente lento

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Hilos en Solaris 2. Recursos necesarios para los tipos de hilosHilos a nivel usuarioSolo requiere un stack y un contador de programaNo involucrar al kernel significa un intercambio rpidoEl kernel solo ve los LWP que soporta los hilos a nivel usuario

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Ejemplo de la arquitectura multihilo de Solaris

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Gestin de hilos bsicaUn hilo tiene :Un identificador (ID)Una pilaUna prioridad de ejecucinUna direccin de inicio de ejecucin.

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Gestin de hilos bsica(POSIX)Se dice que un hilo es dinmico si se puede crear en cualquier instante durante la ejecucin.En POSIX :los hilos se crean dinmicamente con la funcin pthread_create.pthread_exit termina el hilo que la invoca.

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Gestin de hilos bsica (POSIX), ejemplo:Programa que crea un hilo donde muestra el mensaje Hola Mundo

    Para compilar el programa :$ cc -D_REENTRANT thread2.c -o thread2 -lpthread

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    int main(){

    pthread_create(a_thread,funcion_hilo);

    pthread_join(a_thread);

    }funcion_hilo(){ }Crea un hilo nuevoEspera a que termine el hilo creadoHilo principalHilo creado con la llamada pthread_create

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Gestin de hilos bsica(POSIX)Pthread_join()Hilo que ejecuta pthread_join, espera a que termine otro hiloEl hilo principal debe esperar a que terminen todos los hilos creadosSi el hilo principal no espera a que terminen los hilos creados, al terminar termina el proceso con todos los hilos.

    Sistemas Operativos

    Copyright 2006, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. *Other brands and names are the property of their respective owners.

    Hilos en memoriaCdigo(compartido)Datos(compartidos)Int cont=0 (var. Global)Stack (de cada hilo)Int i(var local)Stack (de cada hilo)Int i(var local)

    Sistemas Operativos

    #include

    int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

    pthread_create crea un hilo y lo coloca en la cola de hilos.tid apunta al ID del hilo que se crea.Los atributos del hilo se encapsulan en el objeto atributo al que apunta attr si este es null, el nuevo hilo tendr los atributos por omisin.start_routine, es el nombre de una rutina a la que el hilo invoca.El parmetro que se le especifica a start_routine es arg.

    #include

    void pthread_exit(void *value_ptr);

    La funcin pthread_exit termina el hilo que la invoca. El valor del parmetro value_ptr queda disponible para pthread_join.#include #include #include #include

    void *thread_function(void *arg);

    char message[] = "Hola mundo";

    int main() { int res; pthread_t a_thread; void *thread_result; /* Aqu se crea el hilo */ res = pthread_create(&a_thread, NULL, thread_function, (void *)message); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } printf("Esperando que el hilo termine...\n"); res = pthread_join(a_thread, &thread_result);if (res != 0) { perror("La unin del hilo ha fallado"); exit(EXIT_FAILURE); } printf("Hilo unido, regres %s\n", (char *)thread_result); printf("El mensaje es %s\n", message); exit(EXIT_SUCCESS);}void *thread_function(void *arg) { printf("la funcin del hilo est corriendo. El Argumento fu %s\n", (char *) arg); sleep(3); strcpy(message, "Adios!"); pthread_exit("Gracias por el tiempo del CPU");} #include #include #include #include // Definen funciones para manejo de hilos

    void *thread_function(void *arg); // Funcin donde inicia el hilo

    int cont=0; // Es la misma para ambos hilos // Global est en el segmento de datos

    int main() { // Definicin de variables int res; pthread_t a_thread; // Identificador del hilo void *thread_result; int i; // Es local, por lo tanto est en el segmento de stack de cada hilo

    /* Aqu se crea el hilo */ res = pthread_create(&a_thread, NULL, thread_function,NULL); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); }

    // Hilo principal for(i=1;i0;i--) { printf("%d\n",i); printf("Hilo secundario dice cont=%d\n",cont); sleep(1); }

    pthread_exit("Gracias por el tiempo del CPU");}