programando con hilos posix* intel software college

36
Programando con Hilos POSIX* Intel Software College

Upload: corazon-merino

Post on 22-Apr-2015

11 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Programando con Hilos POSIX* Intel Software College

Programando con Hilos POSIX*

Intel Software College

Page 2: Programando con Hilos POSIX* Intel Software College

2

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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.

Objetivos

Explorar las funciones de la librería Pthreads para crear y sincronizar hilos

Page 3: Programando con Hilos POSIX* Intel Software College

3

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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?

Estándar POSIX.1c

Interfaz en lenguaje C

Los hilos existen dentro del mismo proceso

Todos los hilos son pares

• No es un modelo explícito padre-hijo

• Excepto: “main thread” contiene toda la información del proceso

Page 4: Programando con Hilos POSIX* Intel Software College

4

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 *)• función que será mapeada al hilo

void *arg• argumento que se envía a la función

Page 5: Programando con Hilos POSIX* Intel Software College

5

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 función

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 función

• Si no tiene argumentos, especifica NULL

Verificar códigos de error!

EAGAINEAGAIN – recursos insuficientes para crear el hilo – recursos insuficientes para crear el hiloEINVALEINVAL – atributo inválido – atributo inválido

Page 6: Programando con Hilos POSIX* Intel Software College

6

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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: Creación 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?¿Qué sucede?

Page 7: Programando con Hilos POSIX* Intel Software College

7

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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

Page 8: Programando con Hilos POSIX* Intel Software College

8

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 ESRCH - hilo (pthread_t) no encontrado - hilo (pthread_t) no encontradoEINVALEINVAL - hilo (pthread_t) no unible - hilo (pthread_t) no unible

Page 9: Programando con Hilos POSIX* Intel Software College

9

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 terminación

• No se pueden resetear a ser unibles

Page 10: Programando con Hilos POSIX* Intel Software College

10

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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: Múltiples 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);}

Page 11: Programando con Hilos POSIX* Intel Software College

11

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 *void *threadFunc(void *pArg) { ) { int* p = (int*)pArg;int* p = (int*)pArg; int myNum = *p; printf( “Thread number %d\n”, myNum);}}. . .. . .// from main():// from main():for (int i = 0; i < numThreads; i++) {for (int i = 0; i < numThreads; i++) { pthread_create(&tid[i], NULL, threadFunc, &i);pthread_create(&tid[i], NULL, threadFunc, &i);}}

Page 12: Programando con Hilos POSIX* Intel Software College

12

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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);}

i=0x0001004

pArg=0x0001008

p=0x000100C

mynum=0x0001010

0

0x0001004

1

1

1

Contenido de la dirección 0x0001004Contenido de la dirección 0x0001004

Page 13: Programando con Hilos POSIX* Intel Software College

13

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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.

Solución – Almacenamiento “Local”

void *threadFunc(void *void *threadFunc(void *pArg) ) { { int myNum = *((int*)pArg)(int*)pArg); printf( “Thread number %d\n”, myNum);}}. . .. . .

// from main():// from main():for (int i = 0; i < numThreads; i++) {for (int i = 0; i < numThreads; i++) { tNum[i] = i;tNum[i] = i; pthread_create(&tid[i], NULL, threadFunc, pthread_create(&tid[i], NULL, threadFunc, &tNum[i]&tNum[i]););}}

Page 14: Programando con Hilos POSIX* Intel Software College

14

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 programación 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

Page 15: Programando con Hilos POSIX* Intel Software College

15

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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

ENOMEMENOMEM – memoria insuficiente para mutex – memoria insuficiente para mutexEAGAINEAGAIN – recursos insuficientes (otros que no son – recursos insuficientes (otros que no son memoria)memoria)EPERM EPERM - no privilegios para ejecutar la operación - no privilegios para ejecutar la operación

Page 16: Programando con Hilos POSIX* Intel Software College

16

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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.

Inicialización Alternativa

Puede usarse el inicializador estático

PTHREAD_MUTEX_INITIALIZER

• Usa los atributos por default

El programador debe poner atención al alcance de los mutex

• Deben ser visibles a los hilos

pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER;

Page 17: Programando con Hilos POSIX* Intel Software College

17

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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

Page 18: Programando con Hilos POSIX* Intel Software College

18

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 EINVAL - mutex invalido - mutex invalidoEDEADLKEDEADLK – el hilo llamante ya es dueño del mutex – el hilo llamante ya es dueño del mutex

Page 19: Programando con Hilos POSIX* Intel Software College

19

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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

EINVALEINVAL - mutex es inválido - mutex es inválidoEPERM EPERM - el hilo llamante no es dueño del mutex - el hilo llamante no es dueño del mutex

Page 20: Programando con Hilos POSIX* Intel Software College

20

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 4pthread_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);}

Page 21: Programando con Hilos POSIX* Intel Software College

21

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 Condición

Los semáforos son condicionales en el contador del semáforo

Las variables condición están asociadas con una condición arbitraria

• Las mismas operaciones: wait y signal

Proveen exclusión mutua

Page 22: Programando con Hilos POSIX* Intel Software College

22

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 condición y Mutex

Un mutex está asociado con una variable condición

• Protege la evaluación de la expresión condicional

• Previene condiciones de concurso entre los hilos que están enviando la señal y los hilos que esperan en la variable condición

Page 23: Programando con Hilos POSIX* Intel Software College

23

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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.

Señales perdidas y falsas

Una señal a una variable de condición no se guarda

• Si no hay un hilo esperando, la señal se pierde

• Un hilo puede interbloquearse esperando una señal que no será enviada

Una variable de condición (rara vez) puede recibir señales falsas

• Si las señales se hacen predecibles la ejecución es más lenta

• Se requiere volver a probar la expresión de condición

Page 24: Programando con Hilos POSIX* Intel Software College

24

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 condición

Evita problemas con señales perdidas y señales falsas

adquiere mutex;adquiere mutex;

while (condición es verdadera)while (condición es verdadera)

espera en la variable de condición;espera en la variable de condición;

ejecuta región crítica;ejecuta región crítica;

actualiza condición;actualiza condición;

envía señal a los hilos que esperan;envía señal a los hilos que esperan;

libera mutex;libera mutex;

Se niega la condición se necesita proceder

El mutex se libera automáticamente

cuando el hilo espera

Puede ser

opcional

Page 25: Programando con Hilos POSIX* Intel Software College

25

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 Condición

pthread_cond_init, pthread_cond_destroy

• Inicializa/destruye variables de condición

pthread_cond_wait

• El hilo duerme hasta que se efectúa un signal a la variable de condición

pthread_cond_signal

• Señal que libera la variable de condición

pthread_cond_broadcast

• Broadcast que libera la variable de condición

Page 26: Programando con Hilos POSIX* Intel Software College

26

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 condición

Tipos de datos usados

• pthread_cond_t• La variable de condición

• pthread_condattr_t• Atributos de la variable de condición

Antes de usar, la variable condición (y el mutex) deben inicializarse

Page 27: Programando con Hilos POSIX* Intel Software College

27

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 condición a ser inicializada

const pthread_condattr_t *attr• attributos a ser establecidos en la variable de

conidiciónENOMEMENOMEM - insuficiente memoria para la variable - insuficiente memoria para la variable condicióncondiciónEAGAINEAGAIN - insuficientes recursos (diferentes a la - insuficientes recursos (diferentes a la memoria)memoria)EBUSY EBUSY - variable de condición ya inicializada - variable de condición ya inicializadaEINVALEINVAL - - attrattr inválido inválido

Page 28: Programando con Hilos POSIX* Intel Software College

28

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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.

Inicialización alternativa

Puede usuarse un inicializador estático

PTHREAD_COND_INITIALIZER

• Usa los atributos por default

Los programadores deben estar atentos a la condición y alcance (del mutex)

• Debe ser visible a los hilos

pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;

Page 29: Programando con Hilos POSIX* Intel Software College

29

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 condición a esperar

pthread_mutex_t *mutex• Debe desbloquearse

Page 30: Programando con Hilos POSIX* Intel Software College

30

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 señal en cond

El mutex se desbloquea

• Permite que otros hilos adquiran el lock

• Cuando llega una señal, el mutex será readquirido antes de salir del pthread_cond_wait

EINVAL EINVAL - cond o mutex inválido - cond o mutex inválidoEINVAL EINVAL - mutex diferentes para esperaas concurrentes - mutex diferentes para esperaas concurrentesEINVAL EINVAL - el hilo llamante no es dueño del mutex - el hilo llamante no es dueño del mutex

Page 31: Programando con Hilos POSIX* Intel Software College

31

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 condición a la que se le enviará la señal

Page 32: Programando con Hilos POSIX* Intel Software College

32

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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

Envía una señal a una variable condición, desbloquea un hilo bloqueado

Si no hay hilos esperando, no se toma ninguna acción

• La señal no se guarda para futuros hilos

El hilo que envía la señal no requiere tener el mutex

• Puede ser más eficiente

• Puede haber problemas si se usan prioridades de hilos

EINVAL EINVAL - cond es inválida - cond es inválida

Page 33: Programando con Hilos POSIX* Intel Software College

33

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 condición a recibir la señal

Page 34: Programando con Hilos POSIX* Intel Software College

34

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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 están esperando una variable de condición

Si no hay hilos esperando, no se toma ninguna acción

• Broadcast no se almacena para hilos futuros

El hilo que envía la señal no necesita tener el mutex

EINVAL EINVAL - cond is inválida - cond is inválida

Page 35: Programando con Hilos POSIX* Intel Software College

35

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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

Page 36: Programando con Hilos POSIX* Intel Software College

36

Copyright © 2006, Intel Corporation. All rights reserved.

Programming with POSIX* Threads

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.