Tema 11
Tema 11
Tema 11
1. Introducción
2. Ejecución concurrente
3. Representación de procesos
4. Hilos en Java
5. Hilos en C/POSIX.1c
6. Sincronización
La mayor parte está basada en material original de Alan Burns y Andy Wellings
(Universidad de York ) y Juan Antonio de la Puente (DIT UPM).
• Objetos activos:
– Ejecutan acciones espontáneamente
– Contienen uno o más hilos
• Objetos reactivos:
– Sólo ejecutan acciones cuando son invocados
por otros objetos
– Objetos pasivos:
• Sin control de acceso (se ejecutan sin restricciones)
– Recursos:
• Con control de acceso según su estado interno
• Necesitan un agente de control:
– Recursos protegidos: agente pasivo
» Ej: semáforo
– Servidores: agente activo
• Dos opciones:
– clase java.lang.Thread
• subclase de Object
• proporciona métodos constructores y un método run
– la secuencia principal de control del hilo
• forma de trabajo:
– crear una subclase de Thread y
– redefinir run
– interfaz Runnable:
public interface Runnable {
public abstract void run ();
}
• forma de trabajo:
– crear una clase que implemente Runnable y
– proporcione el método run
while (true) {
Robot.mover (eje, posicion);
ajuste = IU.nuevoAjuste (eje);
posicion += ajuste;
}
}
}
Tema 11 Programación Concurrente y Sincronización 17
Ejemplo: brazo robot en Java, usando la clase Thread. 2
final int ejeX = 0;
final int ejeY = 1;
final int ejeZ = 2;
hiloX.start();
hiloY.start();
hiloZ.start();
...
while (true) {
Robot.mover (eje, posicion);
ajuste = IU.nuevoAjuste (eje);
posicion += ajuste;
}
}
}
hiloX.start();
hiloY.start();
hiloZ.start();
...
pthread_attr_t atributos;
pthread_t hiloX, hiloY, hiloZ;
posicion = 0;
while (1) {
ajuste = nuevo_ajuste (*eje);
posicion += ajuste;
mueve_brazo (+eje, posicion);
}
/* nota: no llamar a pthread_exit. El proceso no termina */
}
X = ejeX;
Y = ejeY;
Z = ejeZ;
if (pthread_attr_init (&atributos) != 0)
exit (-1);
if (pthread_create (&hiloX, &atributos,
(void *) controlador, &X) = 0)
exit (-1);
if (pthread_create (&hiloY, &atributos,
(void *) controlador, &Y) = 0)
exit (-1);
if (pthread_create (&hiloZ, &atributos,
(void *) controlador, &Z) = 0)
exit (-1);
pthread_join (hiloX, (void **) &resultado); /* bloquear main */
}
typedef struct {
pthread_mutex_t mutex;
pthread_cond_t no_lleno;
pthread_cond_t no_vacio;
int datos[TAM_BUFFER];
int indLectura;
int indEscritura;
int cuenta;
} buffer_t;
...
buffer_t miBuffer;
...
miBuffer.cuenta = 0;
miBuffer.indLectura = 0;
miBuffer.indEscritura = 0;
...