Sei sulla pagina 1di 38

Operating System Concepts with Java 7

th
Edition, Nov 15, 2006
Silberschatz, Galvin and Gagne 2007
Captulo 4: Hilos de control
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Captulo 4: Hilos de control
!
Resumen
!
Modelos multi-hilo
!
Detalles con los hilos de control
!
Pthreads
!
Hilos en Windows XP
!
Hilos en Linux
!
Hilos en Java
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Procesos sencillos y multi-hilo
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Beneficios
!
Mejora la respuesta
!
Compartir recursos
!
Economa
!
Utilizacin de arquitectura multi procesador
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hilos de kernel y usuario
!
Hilos de usuarios Administracin de hilos
realizado por biblioteca en nivel usuario.
!
Hilos de kernel Hilos soportados directamente
por el kernel.
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hilos de kernel
Ejemplos
"
Windows XP/2000
"
Solaris
"
Linux
"
Tru64 UNIX
"
Mac OS X
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Modelos multi-hilo
Mapeo de hilos de usuario a kernel:
!
Muchos a uno
!
Uno a uno
!
Muchos a muchos
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Muchos a uno
!
Muchos hilos de usuario mapeados a un
nico hilo de kernel
!
Ejemplos:
"
Solaris Green Threads
"
GNU Portable Threads
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Modelo muchos a uno
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Uno a uno
!
Cada hilo de nivel de usuario se mapea a un
hilo de kernel
!
Ejemplos
"
Windows NT/XP/2000
"
Linux
"
Solaris 9 and later
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Modelo uno a uno
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Modelo muchos a muchos
!
Permite mapear muchos hilos de usuario a
muchos de kernel
!
Permite al sistema operativo crear un nmero
adecuado de hilos
!
Solaris versin 9 y anteriores
!
Windows NT/2000 con el paquete ThreadFiber
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Modelo muchos a muchos
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Modelo de dos niveles
!
Similar a M:M, excepto que permite asociar
un hilo de usuario a uno de kernel
!
Ejemplos
"
IRIX
"
HP-UX
"
Tru64 UNIX
"
Solaris 8 y anteriores
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Modelo de dos niveles
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hilos en Java
!
La JVM administra los hilos en Java
!
En Java se crean hilos
"
Implementando la interfaz Runnable
Public interface Runnable
{
public abstract void run();
}
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hijos en Java Programa ejemplo
class MutableInteger {
private int value;
public int get() {
return value;
}
public void set(int sum) {
this.value = sum;
}
}
class Summation implements Runnable {
private int upper;
private MutableInteger sumValue;
public Summation(int upper, MutableInteger sumValue) {
if (upper < 0)
throw new IllegalArgumentException();
this.upper = upper;
this.sumValue = sumValue;
}
public void run() {
int sum = 0;
for (int i = 0; i <= upper; i++)
sum += i;
sumValue.set(sum);
}
}
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hilos en Java Programa ejemplo
public class Driver {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage Driver <integer>");
System.exit(0);
}
MutableInteger sumObject = new MutableInteger();
int upper = Integer.parseInt(args[0]);
Thread worker = new Thread(new Summation(upper, sumObject));
worker.start();
try {
worker.join();
} catch (InterruptedException ie) { }
System.out.println("The value of " + upper + " is "
+ sumObject.get());
}
}
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Estados de un hilo en Java
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hilos en Java - Productor-Consumidor
public class Factory
{
public Factory()
{
// first create the message buffer
Channel mailBox = new MessageQueue();

// now create the producer and consumer threads
Thread producerThread = new Thread(new Producer(mailBox));
Thread consumerThread = new Thread(new Consumer(mailBox));

producerThread.start();
consumerThread.start();
}
public static void main(String args[]) {
Factory server = new Factory();
}
}
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hilos en Java - Productor-Consumidor
class Producer implements Runnable {
public Producer(Channel m) {
mbox = m;
}

public void run()
{
Date message;
while (true) {
SleepUtilities.nap();
message = new Date();
System.out.println("Producer produced " + message);
// produce an item & enter it into the buffer
mbox.send(message);
}
}

private Channel mbox;
}
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hilos en Java - Productor-Consumidor
class Consumer implements Runnable {
public Consumer(Channel m) {
mbox = m;
}
public void run() {
Date message;
while (true) {
SleepUtilities.nap();
// consume an item from the buffer
System.out.println("Consumer wants to consume.");
message = (Date)mbox.receive();
if (message != null)
System.out.println("Consumer consumed " + message);
}
}

private Channel mbox;
}
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Detalles con los hilos de ejecucin
!
Semntica de llamadas al sistema fork() y exec()
!
Cancelar un hilo de ejecucin
!
Manejo de seales
!
Contenedor de hilos (pool)
!
Datos especficos de cada hilo
!
Activaciones de hilos (planificador)
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Semntica de fork() y termino de hilos
!
fork() duplica el hilo de ejecucin que hace la llamada o
todos los hilos?
!
Opciones para terminar un hilo antes de que termine
!
Dos enfoques generales:
"
Cancelacin asncrona termina el hilo de manera
inmediata
"
Cancelacin diferida permite al hilo objetivo verificar
peridicamente si debe ser cancelando
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Cancelando un hilo de ejecucin
Cancelacin diferida en Java
Interrupcin de hilo
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Cancelando un hijo en Java
Cancelacin diferida en Java
Checando el estado de la interrupcin
public class InterruptibleThread implements Runnable
{
/**
* Este hilo ejecutar mientras no sea
* interrumpido.
*/
public void run() {
while (true) {
/**
* do some work for awhile
*/
if (Thread.currentThread().isInterrupted()) {
System.out.println("I'm interrupted!");
break;
}
}
// clean up and terminate
}
}
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Manejo de seales
!
Las seales se utilizan en sistemas UNIX para notificar
a un proceso que ha ocurrido un evento
!
Se utiliza un manejador de seales para procesarlas
1. La seal es generada por un evento particular
2. La seal se entrega al proceso
3. Se maneja la seal
!
Opciones:
"
Entregar la seal al hilo que aplica
"
Entregar la seal a todos los hilos del proceso
"
Entregar la seal a ciertos hilos en el proceso
"
Asignar un hilo especfico para recibir todas las
seales del proceso
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Contenedores de hilos (pools)
!
Crear un nmero de hilos en un contenedor
donde esperan trabajo
!
Ventajas:
"
Usualmente atienden una solicitud ms
rpido (no hay que crear el hilo)
"
Permite limitar el nmero de hilos en una
aplicacin al tamao del contenedor
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Contenedores de hilos
!
Java ofrece 3 arquitecturas de contenedores:
1. Single thread executor de tamao 1.
2. Fixed thread executor de tamao fijo.
3. Cached thread pool sin lmite de tamao
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Contenedores de hilos
Creando un contenedor de hilos en Java
import java.util.concurrent.*;
public class TPExample {
public static void main(String[] args) {
ExecutorService pool =
java.util.concurrent.Executors.newCachedThreadPool();

for (int i = 0; i < 5; i++)
// just for kicks, use a thread pool
pool.execute(new Task());

// sleep for 5 seconds
try { Thread.sleep(5000); } catch (InterruptedException ie) { }

pool.shutdown();
}
}
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Datos especficos de un hilo
!
Permitir que cada hilo tenga una copia
de sus datos
!
til cuando no tienes control sobre el
proceso de creacin de hilos (v.gr.
Cuando utilizas un contenedor de hilos)
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Datos especficos de un hilo
Datos especficos al hijo en Java
class Service {
private static ThreadLocal errorCode = new ThreadLocal();
public static void transaction() {
// fulfill some kind of transaction service
try { Thread.sleep( (int) (Math.random() * 1000) ); } catch (InterruptedException
ie) { }

try {
/* some operation where an error may occur */
int num = (int) (Math.random() * 2);
double recip = 1 / num;
} catch (Exception e) {
errorCode.set(e);
}
}

/* get the error code for this transaction */
public static Object getErrorCode() {
System.out.println("calling get() " + Thread.currentThread().getName());
return errorCode.get();
}
}
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Activacin de hilos (planificador)
!
Tanto el modelo M:M como el dos niveles requieren
comunicacin para mantener el nmero apropiado de
hilos de kernel asignado a la aplicacin
!
Las activaciones en planificador proveen upcalls un
mecanismo de comunicacin del kernel-biblioteca hilos
!
Esta comunicacin permite mantener el nmero
correcto de hilos de kernel
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Pthreads
!
Estndar API POSIX (IEEE 1003.1c) para la
creacin y sincronizacin de hilos
!
API especifica el comportamiento de una
biblioteca de hilos
!
Tpico encontrarla en sistemas UNIX (Solaris,
Linux, Mac OS X)
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hilos en Windows XP
!
Implementa el mapeo de uno a uno
!
Cada hilo contiene
"
Un id del hilo
"
Conjunto de registros
"
Distintos stacks para kernel y usuario
"
rea de almacenamiento privada
!
El conjunto de registros, stack y rea de
almacenamiento son el contexto de los hilos
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hilos en Windows XP
4.
Silberschatz, Galvin and Gagne 2007
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Hilos en Linux
!
Linux se refiere a los hilos como tareas
!
La creacin de hilos se realiza con la
llamada al sistema clone()
!
clone() permite que una tarea hija
comparta el espacio de direcciones con
el (proceso) padre
Operating System Concepts with Java 7
th
Edition, Nov 15, 2006
Silberschatz, Galvin and Gagne 2007
Fin del Captulo 4

Potrebbero piacerti anche