Вы находитесь на странице: 1из 36

Programando con Hilos POSIX*

Intel Software College

Objetivos
Explorar las funciones de la librera Pthreads para crear y
sincronizar hilos

Programming with POSIX* Threads

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.

Qu son los pthreads?


Estndar POSIX.1c
Interfaz en lenguaje C
Los hilos existen dentro del mismo proceso
Todos los hilos son pares
No es un modelo explcito padre-hijo
Excepto: main thread contiene toda la informacin del
proceso

Programming with POSIX* Threads

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.

pthread_create
int pthread_create(tid, attr, function, arg);

pthread_t *tid

descriptor del hilo creado

const pthread_attr_t *attr

atributos del hilo a crearse

void *(*function)(void *)

funcin que ser mapeada al hilo

void *arg

argumento que se enva a la funcin

Programming with POSIX* Threads

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.

pthread_create Detalles
Inicia un hilo ejecutando la funcin
Descriptor del hilo retornado por medio de la estructura
pthread_t
Especifica NULL para usar los atributos por default
Un solo argumento enviado a la funcin
Si no tiene argumentos, especifica NULL
Verificar cdigos de error!

EAGAIN recursos insuficientes para crear el hilo


EINVAL atributo invlido
5

Programming with POSIX* Threads

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.

Eejemplo: Creacin del hilo


#include <stdio.h>
#include <pthread.h>
void *hello (void * arg) {
printf(Hello Thread\n);
}
main() {
pthread_t tid;
pthread_create(&tid, NULL, hello, NULL);
}

Qu sucede?
6

Programming with POSIX* Threads

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.

Esperando un Thread
int pthread_join(tid, val_ptr);

pthread_t tid

manejador de un hilo a esperar

void **val_ptr

valor de salida devuelto por un hilo

Programming with POSIX* Threads

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.

pthread_join Detalles
Un hilo espera a que un hilo con descriptor tid termine
Solo espera a que un hilo se una
El hilo debe ser unible
Un valor de salida se devuelve del hilo unido
Tipo devuelto es (void *)
Usar NULL si no se espera un valor de retorno

ESRCH - hilo (pthread_t) no encontrado


EINVAL - hilo (pthread_t) no unible
8

Programming with POSIX* Threads

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.

Estados de un hilo
Los hilos Pthread tienen dos estados
Unible (joinable)
Desacoplado (detached)
Por default los hilos son unibles
Los recursos se mantienen hasta el pthread_join
Pueden ser reseteados con atributos o una llamada API
Los hilos desacoplados no pueden unirse
Los recursos pueden reclamarse en la terminacin
No se pueden resetear a ser unibles

Programming with POSIX* Threads

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: Mltiples Hilos


#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 4
void *hello (void *arg) {
printf(Hello Thread\n);
}
main() {
pthread_t tid[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++)
pthread_create(&tid[i], NULL, hello, NULL);

for (int i = 0; i < NUM_THREADS; i++)


pthread_join(tid[i], NULL);

10

Programming with POSIX* Threads

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.

Qu falla?
Qu se muesta de myNum?
void *threadFunc(void *pArg
) {
*
int* p = (int*)pArg;
int myNum = *p;
printf( Thread number %d\n, myNum);
}
. . .
// from main():
for (int i = 0; i < numThreads; i++) {
pthread_create(&tid[i], NULL, threadFunc, &i);
}

11

Programming with POSIX* Threads

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.

for(int i=0;i<numThreads;i++) {
pthread_create(&tid[i], NULL, thread, (void *) &i);
}

void *thread(void *pArg)


{
int *p =(int *) arg;
int mynum = *p;
printf(.. %d\n",mynum);
pthread_exit(NULL);
}

12

Contenido de la direccin 0x0001004


i=0x0001004
pArg=0x0001008

0
1
0x0001004

p=0x000100C

mynum=0x0001010

Programming with POSIX* Threads

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.

Solucin Almacenamiento Local

void *threadFunc(void *pArg


)
*
{
int myNum = *((int*)pArg);
(int*)pArg)
printf( Thread number %d\n, myNum);
}
. . .
// from main():
for (int i = 0; i < numThreads; i++) {
tNum[i] = i;
pthread_create(&tid[i], NULL, threadFunc, &tNum[i]);
}

13

Programming with POSIX* Threads

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.

Pthreads Variables Mutex


Simple, flexible, y eficiente
Permiten estructuras de programacin correctas para evitar
condiciones de concurso
Nuevos tipos
pthread_mutex_t
Variable mutex

pthread_mutexattr_t
Atributos de mutex

Antes de usar, mutex debe ser inicializada

14

Programming with POSIX* Threads

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.

pthread_mutex_init
int pthread_mutex_init( mutex, attr );

pthread_mutex_t *mutex

mutex a ser inicializada

const pthread_mutexattr_t *attr

atributos a ser establecidos a mutex

ENOMEM memoria insuficiente para mutex


EAGAIN recursos insuficientes (otros que no son
memoria)
EPERM - no privilegios para ejecutar la operacin
15

Programming with POSIX* Threads

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.

Inicializacin Alternativa
Puede usarse el inicializador esttico
PTHREAD_MUTEX_INITIALIZER
pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER;
Usa los atributos por default

El programador debe poner atencin al alcance de los mutex


Deben ser visibles a los hilos

16

Programming with POSIX* Threads

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.

pthread_mutex_lock
int pthread_mutex_lock( mutex );

pthread_mutex_t *mutex
mutex que intenta hacer el lock

17

Programming with POSIX* Threads

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.

pthread_mutex_lock Detalles
Intenta hacer el lock del mutex
Si el mutex est bloqueado por otro hilo, el hilo que llama al
lock se bloquea
Mutex es detenido por el hilo que lo llama hasta que se
desbloquea
Mutex lock/unlock deben ser pares, si no puede ocurrir un
interbloqueo

EINVAL - mutex invalido


EDEADLK el hilo llamante ya es dueo del mutex
18

Programming with POSIX* Threads

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.

pthread_mutex_unlock
int pthread_mutex_unlock( mutex );

pthread_mutex_t *mutex

mutex a ser desbloqueado

EINVAL - mutex es invlido


EPERM - el hilo llamante no es dueo del mutex
19

Programming with POSIX* Threads

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.

Exjemplo: Uso del mutex


#define NUMTHREADS 4
pthread_mutex_t gMutex; // porque debe ser global?
int g_sum = 0;
void *threadFunc(void *arg)
{
int mySum = bigComputation();
pthread_mutex_lock( &gMutex );
g_sum += mySum;
// los hilos acceden uno a la vez
pthread_mutex_unlock( &gMutex );
}
main() {
pthread_t hThread[NUMTHREADS];
pthread_mutex_init( &gMutex, NULL );
for (int i = 0; i < NUMTHREADS; i++)
pthread_create(&hThread[i],NULL,threadFunc,NULL);

for (int i = 0; i < NUMTHREADS; i++)


pthread_join(hThread[i]);
printf (Global sum = %f\n, g_sum);

20

Programming with POSIX* Threads

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.

Variables Condicin
Los semforos son condicionales en el contador del semforo
Las variables condicin estn asociadas con una condicin
arbitraria
Las mismas operaciones: wait y signal
Proveen exclusin mutua

21

Programming with POSIX* Threads

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.

Variable condicin y Mutex


Un mutex est asociado con una variable condicin
Protege la evaluacin de la expresin condicional
Previene condiciones de concurso entre los hilos que estn
enviando la seal y los hilos que esperan en la variable
condicin

22

Programming with POSIX* Threads

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.

Seales perdidas y falsas


Una seal a una variable de condicin no se guarda
Si no hay un hilo esperando, la seal se pierde
Un hilo puede interbloquearse esperando una seal que no
ser enviada
Una variable de condicin (rara vez) puede recibir seales
falsas
Si las seales se hacen predecibles la ejecucin es ms lenta
Se requiere volver a probar la expresin de condicin

23

Programming with POSIX* Threads

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.

Algoritmo de variables de condicin


Evita problemas con seales perdidas y seales falsas
Se niega la condicin
se necesita proceder

adquiere mutex;
El mutex se libera
while (condicin es verdadera)
automticamente
cuando el hilo espera
espera en la variable de condicin;
ejecuta regin crtica;
actualiza condicin;
Puede
ser
enva seal a los hilos que esperan;
opcional
libera mutex;
24

Programming with POSIX* Threads

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.

Variables Condicin
pthread_cond_init, pthread_cond_destroy
Inicializa/destruye variables de condicin
pthread_cond_wait
El hilo duerme hasta que se efecta un signal a la variable de
condicin
pthread_cond_signal
Seal que libera la variable de condicin
pthread_cond_broadcast
Broadcast que libera la variable de condicin

25

Programming with POSIX* Threads

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.

Tipos de variables de condicin


Tipos de datos usados

pthread_cond_t
La variable de condicin

pthread_condattr_t
Atributos de la variable de condicin

Antes de usar, la variable condicin (y el mutex) deben


inicializarse

26

Programming with POSIX* Threads

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.

pthread_cond_init
int pthread_cond_init( cond, attr );

pthread_cond_t *cond

variable condicin a ser inicializada

const pthread_condattr_t *attr

attributos a ser establecidos en la variable de conidicin


ENOMEM - insuficiente memoria para la variable
condicin
EAGAIN - insuficientes recursos (diferentes a la
memoria)
EBUSY - variable de condicin ya inicializada
EINVAL - attr invlido
27

Programming with POSIX* Threads

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.

Inicializacin alternativa
Puede usuarse un inicializador esttico
PTHREAD_COND_INITIALIZER
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
Usa los atributos por default

Los programadores deben estar atentos a la condicin y alcance


(del mutex)
Debe ser visible a los hilos

28

Programming with POSIX* Threads

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.

pthread_cond_wait
int pthread_cond_wait( cond, mutex );

pthread_cond_t *cond
Variable condicin a esperar

pthread_mutex_t *mutex
Debe desbloquearse

29

Programming with POSIX* Threads

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.

pthread_cond_wait Detalles
El hilo se bloquea esperando una seal en cond
El mutex se desbloquea
Permite que otros hilos adquiran el lock
Cuando llega una seal, el mutex ser readquirido antes de
salir del pthread_cond_wait

EINVAL - cond o mutex invlido


EINVAL - mutex diferentes para esperaas concurrentes
EINVAL - el hilo llamante no es dueo del mutex
30

Programming with POSIX* Threads

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.

pthread_cond_signal
int pthread_cond_signal( cond );

pthread_cond_t *cond
Variable condicin a la que se le enviar la seal

31

Programming with POSIX* Threads

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.

pthread_cond_signal Detalles
Enva una seal a una variable condicin, desbloquea un hilo
bloqueado
Si no hay hilos esperando, no se toma ninguna accin
La seal no se guarda para futuros hilos
El hilo que enva la seal no requiere tener el mutex
Puede ser ms eficiente
Puede haber problemas si se usan prioridades de hilos

EINVAL - cond es invlida


32

Programming with POSIX* Threads

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.

pthread_cond_broadcast
int pthread_cond_broadcast( cond );

pthread_cond_t *cond
variable condicin a recibir la seal

33

Programming with POSIX* Threads

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.

pthread_cond_broadcast detalles
Desbloquea todos los hilos que estn esperando una variable de
condicin
Si no hay hilos esperando, no se toma ninguna accin
Broadcast no se almacena para hilos futuros
El hilo que enva la seal no necesita tener el mutex

EINVAL - cond is invlida

34

Programming with POSIX* Threads

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.

Programando con hilos POSIX*


Temas cubiertos
Como crear hilos que hagan trabajo encapsulado dentro de las
funciones
Coordinar acceso compartido entre hilos para evitar condiciones
de concurso

35

Programming with POSIX* Threads

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.

36

Programming with POSIX* Threads

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.

Вам также может понравиться