semÁforos en procesos

Upload: inward-brocoli-ericq

Post on 03-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 SEMFOROS EN PROCESOS

    1/5

    SEMFOROS EN PROCESOSSemforo es una VARIAB LE DE tipo ab stracto de datos ) que con sti tuy e elmtod o clsic o para restrin gir o p erm itir el acces o a recur so s comp artid os(por ejemplo , un recurso de almacenamiento del sistema o var iables del

    cdigo fuente) en un en torn o de m ult ip roces amiento (en el que se ejecut arnvar ios procesos c oncu rrentemente). Fueron inv entados por Eds gerDijkstra en 1965 y se usaro n po r primera vez en el sistema op erativoTHEOSPROGRAMA DE PROCESOS DE SEMAFOROS (PROBLEMA DE LOSFILOSOSFOS)#include#define N 5#def ine IZQ (i+N-1)%N#define DER (i+1)%N

    #def ine pensando 0#define hambr e 1#def ine com iendo 2typedef int semaphore;int estado(N);semaforo m utex=1;semaforo s[N];void f i loso fo( int i){while(true){

    pensar();tomar_tenedor(i) ;comer();dejar_tenedor(i);

    }}void tomar_tenedor( int i){dow(&mutex);estado[i ]=hambre;

    probar(i) ;up(&mutex);down(&s[ i ] ) ;

    }void dejar_tenedo r(int i){down(&mutex);

  • 7/28/2019 SEMFOROS EN PROCESOS

    2/5

    estado[ i ]=pensando;probar(IZQ);probar(DER);up(&mutex);

    }

    void probar( i){

    if(estado[i ]==hambre&&estado[IZQ]!=comiendo&&estado[DER]!=comiendo){estado[ i ]=comiendo;up(&s[i ]) ;

    }}

    El prob lema Productor/Consum idor

    El problema Producto r/Consum idor es uno de los ejemp los

    cl asicos de acceso a recu rso s compart ido s q ue debe arbitrarse

    med iante alg un mecanismo de conc urrenc ia que implemente la

    exc lu s i onm u tua.

    A co ntinu aci on se propo rcio nan version es que imp lementan la

    exc lus i on m u tu a med ian te la u ti lizac i on de :

    Monito res Java: m on itores restr in gido s a u na un ica variable de

    condicion implcita.

    Monitores Signal and Con t inue: modelo g eneral de monitores co n

    m as de un a var iab le de co nd ic i on .

    El problema Productor/Consumido r cons iste en el acceso

    conc urrente por parte de procesos prod uctores y procesos

    cons um idores so bre un recurso com un que resul ta ser un buffer deelementos. L os

    prod uctores tratan de introd ucir elementos en el buffer de uno enuno , y los con sum idores tratan de

    extraer elementos de u no en uno

  • 7/28/2019 SEMFOROS EN PROCESOS

    3/5

    ALGORITIMO QUE EJECUTA UN PRODUCTOR Y CONSUMIDOR EN

    C++

    #includ e

    #includ e

    using namespace con currency;using n amespace std;

    // Demonstrat es a bas ic ag ent that produces val ues .

    class prod ucer_agent : pub l ic agent

    {

    publ ic :

    explici t pro duc er_agent(ITarget& target, un sign ed int coun t,

    int sentinel)

    : _target(target)

    , _cou nt(count)

    , _sentin el(sentinel)

    {

    }

    protected:

    void run ()

    {

    // Send the value o f each loop iter at ion to the tar get bu ffer.

    wh ile (_count > 0){

    send (_target, stat ic_cast(_coun t));

    --_count;

    }

    // Send the sentinel value.

    send(_target, _senti nel);

    // Set the agen t to the f in ished state.

    done();

    }private:

    // The tar get bu ffer to write to .

    ITarget& _target;

    // The number o f values to send .

    uns igned int _count;

  • 7/28/2019 SEMFOROS EN PROCESOS

    4/5

    // The sent inel value, which in forms the cons umer agent to stop

    process ing.

    int _sentinel;

    };

    // Demonstrat es a bas ic ag ent that consumes values .class cons umer_agent : pub l ic agent

    {

    publ ic :

    explici t consumer_agent(ISourc e& sou rce, int sentinel)

    : _sou rce(sourc e)

    , _sentin el(sentinel)

    {

    }

    // Retr ieves the av er ag e of all recei ved val ues .

    int average()

    {

    retu rn receive(_average);

    }

    protected:

    void run ()

    {

    // The sum of al l values .int sum = 0;

    // The count of val ues rec eived .

    int cou nt = 0;

    // Read from the source b lock until we receive the

    // sen tinel val ue.

    in t n;

    while ((n = receive(_sou rce)) != _sen tinel)

    {

    sum += n;++count;

    }

    // Wr ite the average to the messag e buffer .

    send (_average, sum / coun t);

    // Set the agen t to the f in ished state.

  • 7/28/2019 SEMFOROS EN PROCESOS

    5/5

    done();

    }

    private:

    // The source buffer to read from .

    ISour ce& _sour ce;// The sen tinel value, wh ich in fo rms the ag ent to s top proces s ing .

    int _sentinel;

    // Ho lds the average of al l rec eived values .

    sing le_assig nment _average;

    };

    int wm ain()

    {

    // In fo rms the consumer agen t to stop proces s ing .

    con st int s ent inel = 0;

    // The number o f values fo r the producer agen t to send.

    con st unsig ned int count = 100;

    // A message buffer that is shar ed by the agen ts .

    unb oun ded_buffer buffer ;

    // Creat e an d start the producer and consumer ag en ts .

    pro du cer_agent pro duc er(buffer, cou nt, sentinel);

    con sum er_agent co nsum er(buf fer , sent inel);

    producer.start();consumer.start();

    // Wait fo r the agen ts to fin ish .

    agent::wait(&producer);

    agent: :wai t (&consumer);

    // Pr in t the av erag e.

    wc ou t