hilos posix

Upload: angel-lopez

Post on 01-Jun-2018

247 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 Hilos POSIX

    1/36

    Programando con Hilos POSIX*

    Intel Software College

  • 8/9/2019 Hilos POSIX

    2/36

    2Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    Objetivos

    %&plorar las fun"iones de la li rer'a (threads para "rear ysin"roni)ar hilos

  • 8/9/2019 Hilos POSIX

    3/36

    3Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    Qu son los pthreads?

    %st*ndar ($SI+. "Interfa) en lengua-e C

    os hilos e&isten dentro del mismo pro"eso

    /odos los hilos son pares

    1o es un modelo e&pl'"ito padre hi-o

    %&"epto3 4main thread5 "ontiene toda la informa"i n delpro"eso

  • 8/9/2019 Hilos POSIX

    4/36

    4Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread create

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

    pthread_t *tid des"riptor del hilo "reado

    const pthread_attr_t *attratri utos del hilo a "rearse

    void *(*function)(void *)fun"i n 7ue ser* mapeada al hilo

    void *argargumento 7ue se env'a a la fun"i n

  • 8/9/2019 Hilos POSIX

    5/36

    5Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread create !etalles

    Ini"ia un hilo e-e"utando la fun"i n8es"riptor del hilo retornado por medio de la estru"tura

    pthread_t%spe"ifi"a NULL para usar los atri utos por default

    !n solo argumento enviado a la fun"i nSi no tiene argumentos, espe"ifi"a NULL

    9erifi"ar " digos de error:

    EAGAINEAGAIN recursos insuficientes para crear el hilo recursos insuficientes para crear el hiloEINVALEINVAL atributo invlido atributo invlido

  • 8/9/2019 Hilos POSIX

    6/36

    6Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    "ejemplo# $reaci%n del hilo

    inc!ude "stdio#h$

    inc!ude "pthread#h$

    void *he!!o (void * arg) % printf(&'e!!o hread n );

    +

    ain() % pthread_t tid;

    pthread_create(-tid, NULL, he!!o, NULL);

    +

    Qu sucede?Qu sucede?

  • 8/9/2019 Hilos POSIX

    7/36

    7Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    "sperando un &hread

    int pthread_.oin(tid, va!_ptr);

    pthread_t tid mane-ador de un hilo a esperar

    void **va!_ptrvalor de salida devuelto por un hilo

  • 8/9/2019 Hilos POSIX

    8/36

    8Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread join !etalles

    !n hilo espera a 7ue un hilo "on des"riptor tid termineSolo espera a 7ue un hilo se una

    %l hilo de e ser unible

    !n valor de salida se devuelve del hilo unido

    /ipo devuelto es (void *)!sar NULL si no se espera un valor de retorno

    E/01'E/01' - hilo (pthread_t) no encontrado- hilo (pthread_t) no encontradoEINVALEINVAL - hilo (pthread_t) no unible- hilo (pthread_t) no unible

  • 8/9/2019 Hilos POSIX

    9/36

    9Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    "stados de un hilo

    os hilos (thread tienen dos estados Unible (joinable)

    Desacoplado (detached)

    (or default los hilos son uni les

    os re"ursos se mantienen hasta el pthread_.oin(ueden ser reseteados "on atri utos o una llamada A(I

    os hilos desa"oplados no pueden unirse

    os re"ursos pueden re"lamarse en la termina"i n1o se pueden resetear a ser unibles

  • 8/9/2019 Hilos POSIX

    10/36

    10Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    "jemplo# '(ltiples Hilos

    inc!ude "stdio#h$ inc!ude "pthread#h$ define NU2_ '0EA3/ 4

    void *he!!o (void *arg) % printf(&'e!!o hread n );

    + ain() %

    pthread_t tid5NU2_ '0EA3/6; for (int i 7 8; i " NU2_ '0EA3/; i99) pthread_create(-tid5i6, NULL, he!!o, NULL);

    for (int i 7 8; i " NU2_ '0EA3/; i99) pthread_.oin(tid5i6, NULL);+

  • 8/9/2019 Hilos POSIX

    11/36

    11Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    Qu )alla?

    ;

    void *thread:unc(void *void *thread:unc(void *pArg ) %) %int* p 7 (int*)pArg;int* p 7 (int*)pArg;

    int Nu 7 *p; printf( & hread nu > fro ain()?>> fro ain()?for (int i 7 8; i " nu hreads; i99) %for (int i 7 8; i " nu hreads; i99) %

    pthread_create(-tid5i6, NULL, thread:unc, -i); pthread_create(-tid5i6, NULL, thread:unc, -i);++

  • 8/9/2019 Hilos POSIX

    12/36

    12Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    for(int i78;i"nu hreads;i99) % pthread_create(-tid5i6, NULL, thread, (void *) -i); +

    void *thread(void *pArg)% int *p 7(int *) arg; int nu 7 *p;

    printf(&@@## =d n , nu );

    pthread_eBit(NULL);+

    i 0!0001004

    pArg 0!0001008

    p 0!000100"

    mynum 0!0001010

    0

    0!0001004

    1

    1

    1

    Contenido de la direccin 0x0001004Contenido de la direccin 0x0001004

  • 8/9/2019 Hilos POSIX

    13/36

    13Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    Soluci%n +lmacenamiento ,-ocal.

    void *thread:unc(void *void *thread:unc(void *pArg ))%%

    int Nu 7 *( (int*)pArg)(int*)pArg); printf( & hread nu > fro ain()?>> fro ain()?for (int i 7 8; i " nu hreads; i99) %for (int i 7 8; i " nu hreads; i99) % tNu 5i6 7 i;tNu 5i6 7 i;

    pthread_create(-tid5i6, NULL, thread:unc, pthread_create(-tid5i6, NULL, thread:unc, -tNu 5i6-tNu 5i6 ););++

  • 8/9/2019 Hilos POSIX

    14/36

    14Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    Pthreads /ariables 'ute0

    Simple, fle&i le, y efi"iente(ermiten estru"turas de programa"i n "orre"tas para evitar"ondi"iones de "on"urso

    1uevos tipos pthread_ uteB_t9aria le mute&

    pthread_ uteBattr_tAtri utos de mute&

    Antes de usar, mute& de e ser ini"iali)ada

  • 8/9/2019 Hilos POSIX

    15/36

    15Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread mute0 init

    int pthread_ uteB_init( uteB, attr );

    pthread_ uteB_t * uteBmute& a ser ini"iali)ada

    const pthread_ uteBattr_t *attratri utos a ser esta le"idos a mute&

    ENC2E2 ENC2E2 memoria insuficiente para mutex memoria insuficiente para mutexEAGAINEAGAIN recursos insuficientes (otros que no son recursos insuficientes (otros que no sonmemoria)memoria)EDE02EDE02 - no privile ios para e!ecutar la operaci"n- no privile ios para e!ecutar la operaci"n

  • 8/9/2019 Hilos POSIX

    16/36

    16Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    Iniciali1aci%n +lternativa

    (uede usarse el ini"iali)ador est*ti"oD '0EA3_2U E _INI IALIFE0

    !sa los atri utos por default

    %l programador de e poner aten"i n al al"an"e de los mute&

    8e en ser visi les a los hilos

    pthread_ uteB_t tB 7 D '0EA3_2U E _INI IALIFE0;

  • 8/9/2019 Hilos POSIX

    17/36

    17Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread mute0 loc2

    int pthread_ uteB_!ocH( uteB );

    pthread_ uteB_t * uteBmute& 7ue intenta ha"er el lo"k

  • 8/9/2019 Hilos POSIX

    18/36

    18Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread mute0 loc2 !etalles

    Intenta ha"er el lo"k del mute&Si el mute& est* lo7ueado por otro hilo, el hilo 7ue llama allo"k se lo7uea

    ?ute& es detenido por el hilo 7ue lo llama hasta 7ue sedes lo7uea

    ?ute& lo"k@unlo"k de en ser pares, si no puede o"urrir uninter lo7ueo

    EINVALEINVAL - mutex invalido- mutex invalidoE3EA3LE3EA3L el hilo llamante #a es due$o del mutex el hilo llamante #a es due$o del mutex

  • 8/9/2019 Hilos POSIX

    19/36

    19Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread mute0 unloc2

    int pthread_ uteB_un!ocH( uteB );

    pthread_ uteB_t * uteBmute& a ser des lo7ueado

    EINVALEINVAL - mutex es invlido- mutex es invlidoEDE02EDE02 - el hilo llamante no es due$o del mutex- el hilo llamante no es due$o del mutex

  • 8/9/2019 Hilos POSIX

    20/36

    20Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    "0jemplo# 3so del mute0

    define NU2 '0EA3/ 4 pthread_ uteB_t g2uteB; >> JporKue de

  • 8/9/2019 Hilos POSIX

    21/36

    21Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    /ariables $ondici%n

    os sem*foros son "ondi"ionales en el "ontador del sem*foroas varia les "ondi"i n est*n aso"iadas "on una "ondi"i n

    ar itraria

    as mismas opera"iones3 wait y signal

    (roveen e&"lusi n mutua

  • 8/9/2019 Hilos POSIX

    22/36

    22Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    /ariable condici%n 4 'ute0

    !n mute& est* aso"iado "on una varia le "ondi"i n(rotege la evalua"i n de la e&presi n "ondi"ional

    (reviene "ondi"iones de "on"urso entre los hilos 7ue est*nenviando la se al y los hilos 7ue esperan en la varia le"ondi"i n

  • 8/9/2019 Hilos POSIX

    23/36

    23Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    Se5ales perdidas 4 )alsas

    !na se al a una varia le de "ondi"i n no se guardaSi no hay un hilo esperando, la se al se pierde

    !n hilo puede inter lo7uearse esperando una se al 7ue noser* enviada

    !na varia le de "ondi"i n Brara ve) puede re"i ir se alesfalsas

    Si las se ales se ha"en prede"i les la e-e"u"i n es m*s lenta

    Se re7uiere volver a pro ar la e&presi n de "ondi"i n

  • 8/9/2019 Hilos POSIX

    24/36

    24Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    +lgoritmo de variables de condici%n

    %vita pro lemas "on se ales perdidas y se ales falsas

    adquiere mutex%adquiere mutex%&hile (condici"n es verdadera)&hile (condici"n es verdadera) espera en la variable de condici"n%espera en la variable de condici"n%e!ecuta re i"n cr'tica%e!ecuta re i"n cr'tica%

    actuali a condici"n%actuali a condici"n%env'a se$al a los hilos que esperan%env'a se$al a los hilos que esperan%libera mutex%libera mutex%

    e nie a la condici"nse necesita proceder

    *l mutex se liberaautomticamente

    cuando el hilo espera

    +uedeseropcional

  • 8/9/2019 Hilos POSIX

    25/36

    25Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    /ariables $ondici%n

    pthread_cond_init, pthread_cond_destroIni"iali)a@destruye varia les de "ondi"i n

    pthread_cond_ ait%l hilo duerme hasta 7ue se efe"tDa un signal a la varia le de

    "ondi"i n pthread_cond_signa!

    Se al 7ue li era la varia le de "ondi"i n

    pthread_cond_

  • 8/9/2019 Hilos POSIX

    26/36

    26Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    &ipos de variables de condici%n

    /ipos de datos usados pthread_cond_t

    a varia le de "ondi"i n

    pthread_condattr_tAtri utos de la varia le de "ondi"i n

    Antes de usar, la varia le "ondi"i n By el mute& de enini"iali)arse

  • 8/9/2019 Hilos POSIX

    27/36

    27Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread cond init

    int pthread_cond_init( cond, attr );

    pthread_cond_t *cond varia le "ondi"i n a ser ini"iali)ada

    const pthread_condattr_t *attrattri utos a ser esta le"idos en la varia le de "onidi"i n

    ENC2E2 ENC2E2 - insuficiente memoria para la variable- insuficiente memoria para la variablecondici"ncondici"nEAGAINEAGAIN - insuficientes recursos (diferentes a la- insuficientes recursos (diferentes a lamemoria)memoria)EOU/PEOU/P - variable de condici"n #a iniciali ada- variable de condici"n #a iniciali adaEINVALEINVAL -- attrattr invlidoinvlido

  • 8/9/2019 Hilos POSIX

    28/36

    28Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    Iniciali1aci%n alternativa

    (uede usuarse un ini"iali)ador est*ti"oD '0EA3_1CN3_INI IALIFE0

    !sa los atri utos por default

    os programadores de en estar atentos a la "ondi"i n y al"an"eBdel mute&

    8e e ser visi le a los hilos

    pthread_cond_t cond 7 D '0EA3_1CN3_INI IALIFE0;

  • 8/9/2019 Hilos POSIX

    29/36

    29Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread cond 6ait

    int pthread_cond_ ait( cond, uteB );

    pthread_cond_t *cond 9aria le "ondi"i n a esperar

    pthread_ uteB_t * uteB8e e des lo7uearse

  • 8/9/2019 Hilos POSIX

    30/36

    30Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread cond 6ait !etalles

    %l hilo se lo7uea esperando una se al en cond %l mute& se des lo7uea

    (ermite 7ue otros hilos ad7uiran el lo"k

    Cuando llega una se al, el mute& ser* read7uirido antes de

    salir del pthread_cond_ ait

    EINVALEINVAL - cond o mutex invlido- cond o mutex invlidoEINVALEINVAL - mutex diferentes para esperaas concurrentes- mutex diferentes para esperaas concurrentesEINVALEINVAL - el hilo llamante no es due$o del mutex- el hilo llamante no es due$o del mutex

  • 8/9/2019 Hilos POSIX

    31/36

    31Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread cond signal

    int pthread_cond_signa!( cond );

    pthread_cond_t *cond 9aria le "ondi"i n a la 7ue se le enviar* la se al

  • 8/9/2019 Hilos POSIX

    32/36

    32Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread cond signal !etalles

    %nv'a una se al a una varia le "ondi"i n, des lo7uea un hilolo7ueado

    Si no hay hilos esperando, no se toma ninguna a""i n

    a se al no se guarda para futuros hilos

    %l hilo 7ue env'a la se al no re7uiere tener el mute&(uede ser m*s efi"iente

    (uede ha er pro lemas si se usan prioridades de hilos

    EINVALEINVAL - cond es invlida- cond es invlida

  • 8/9/2019 Hilos POSIX

    33/36

    33Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread cond broadcast

    int pthread_cond_

  • 8/9/2019 Hilos POSIX

    34/36

    34Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    pthread cond broadcast detalles

    8es lo7uea todos los hilos 7ue est*n esperando una varia le de"ondi"i n

    Si no hay hilos esperando, no se toma ninguna a""i n

    Eroad"ast no se alma"ena para hilos futuros

    %l hilo 7ue env'a la se al no ne"esita tener el mute&

    EINVALEINVAL - cond is invlida- cond is invlida

  • 8/9/2019 Hilos POSIX

    35/36

    35Copyright 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 su sidiaries i n the !nited States or other "ountries. # $ther rands and names are the property of their respe"tive owners.

    Programando con hilos POSIX*&emas cubiertos

    Como "rear hilos 7ue hagan tra a-o en"apsulado dentro de lasfun"iones

    Coordinar a""eso "ompartido entre hilos para evitar "ondi"ionesde "on"urso

  • 8/9/2019 Hilos POSIX

    36/36

    36

    Programming with POSIX* Threads