2010-10-03 52 views
7

Para una tarea asignada, necesito programar el siguiente escenario. Esto se hará usando semáforos usando BACI (que es C--)Semáforos y programación simultánea

Hay 2 baños unisex que pueden albergar a 4 personas cada uno. Como es unisex, solo personas del mismo sexo pueden estar en el baño al mismo tiempo y FIFO no es importante. Tengo el "algoritmo" básico en mi cabeza para manejar 4 hombres y 4 mujeres para 1 baño. Pero no sé cómo codificar esto. Cualquier ayuda sería muy apreciada. Esto es lo que tengo. Se proporcionaron

Woman: 

Check to see if there are any men in the restroom. If so "wait". 
If no men check to see if there are 4 people. If so "wait". 
If no men and not 4 use restroom. When leaving signal there is a vacancy. 
If last woman signal the men if they are waiting if not signal the woman. 


Man: 

check to see if there are any woman in the restroom. if so "wait" 
If no woman check to see if there are 4 people. If so "wait". 
If no woman and not 4 use restroom. when leaving signal there is a vacancy. 
if last man signal the women if they are waiting if not signal the men. 

Estas instrucciones adicionales

  • Uso azar para bucles para simular el paso del tiempo en los lugares apropiados. Esto puede hacerse fácilmente mediante el uso de una función de retardo:

    void Delay (void) 
    { 
        int i; 
        int DelayTime; 
        DelayTime = random (DELAY); 
        for (i = 0; i < DelayTime; i++): 
    } 
    
  • donde const int = RETRASO un número de 10 a 100.

  • impresión y la generación de formato muy bien e imprimir los mensajes de tal manera que mediante la lectura la salida, uno puede rastrear el orden de ejecución.
  • Establezca los procesos en bucle para siempre y use el control C (o control de interrupción) para detener su programa.
+0

qué tiene que ser óptima? –

+0

No. Pero no puede tener inanición. Entonces los hombres y las mujeres deben usar el baño de manera justa. – Jen

+0

No estoy seguro si estás preocupado por la inanición, pero estoy bastante seguro de que tu algoritmo tiene un problema de inanición. Imagine el caso en que aparece un hombre mientras una mujer ya está en el baño, y un flujo constante de mujeres sigue apareciendo para que el baño nunca se vacíe. –

Respuesta

0

Esto es lo que tengo. Esto permite 1 persona en el baño a la vez sin interbloqueo o inanición. Necesito ayuda con cómo hacerlo para que 4 personas puedan estar en el baño a la vez.

const int Delayx = 60; 
int i; 
semaphore max_capacity; 
semaphore woman; 
semaphore man; 
semaphore mutex; 

void Delay(void) 
{ 
    int DelayTime; 
    DelayTime = random(Delayx); 
    for (i = 0; i<DelayTime; i++); 
} 

void Woman(void) 
{ 
    wait(woman); 
    wait(max_capacity); 
    wait(mutex); 
    cout << "A Woman has entered Restroom"<<endl; 
    Delay(); 
    cout << "A woman has exited Restroom"<<endl; 
    signal(mutex); 
    signal(max_capacity); 
    signal(man); 
} 

void Man(void) 
{ 
    wait(man); 
    wait(max_capacity); 
    wait(mutex); 
    cout <<"A Man has entered the Restroom"<<endl; 
    Delay(); 
    cout << "A man has exited the Restroom"<<endl; 
    signal(mutex); 
    signal(max_capacity); 
    signal(woman); 
} 

void main() 
{ 
    initialsem(woman,1); 
    initialsem(man,1); 
    initialsem(max_capacity,4); 
    initialsem(mutex,1); 
    cobegin 
    { 
     Woman(); Woman(); Woman(); Woman(); Woman(); Woman(); Woman(); Woman(); Man(); Man(); Man(); Man(); Man(); Man(); Man(); Man(); 
    } 
} 
1

Puesto que usted quiere saber how to code your algorithm for 1 restroom, que lo han hecho en C. Será una tarea bastante sencilla para convertirlo en C--, como todas las construcciones de semáforos parecen bastante similares.

Por lo que pude hacer de su respuesta,

C: sem_wait() C--: wait() 
    sem_post()  signal() 
    sem_t   semaphore() 
    sem_init()  initialsem() 

Tenga en cuenta, como se ha dicho, que han trabajado el problema de 1-baño solamente. Como esto es tarea, espero que lo expanda usted mismo en el formulario 2-sanos.

Trabajar el propio camino de la Readers-writers problem a nuestro problema "unisex de baños", que hacen uso de las siguientes variables globales:

int mcount,wcount; // count of number of men/women in restroom 
sem_t x,y,z;  // semaphores for updating mcount & wcount values safely 
sem_t wsem,msem; // semaphores to block other genders' entry 
sem_t cap;   // capacity of the restroom 

La incorporación de estos semáforos & contadores en la función man hilo,

void *man(void *param) 
{   
    sem_wait(&z);     
     sem_wait(&msem);   
      sem_wait(&x); 
       mcount++; 
       if(mcount==1) 
       { sem_wait(&wsem); } // first man in, make women wait 
      sem_post(&x); 
     sem_post(&msem); 
    sem_post(&z); 

    sem_wait(&cap); //wait here, if over capacity 

    printf("\t\tman in!\n"); 
    delay(); 
    printf("\t\t\tman out!\n"); 

    sem_post(&cap); //one man has left, increase capacity 

    sem_wait(&x); 
     mcount--; 
     if(mcount==0) 
     {sem_post(&wsem);} // no man left, signal women 
    sem_post(&x); 
} 

Del mismo modo, la función de hilo de mujer, sustituye mcount con wcount, msem con wsem y x con y. Sólo z permanece como está en la función man, de modo que ambos manwoman subprocesos cola en el mismo semáforo común.(Debido a esto, el código invariablemente tiene FIFO-como comportamiento, lo que asegura equidad/no-inanición)

El código completo es el siguiente: (Para compilar, utilice gcc filename -lpthread)

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 
#include <semaphore.h> 

int mcount,wcount; 
sem_t x,y,z,wsem,msem,cap; 

void delay(void) 
{ 
    int i; 
    int delaytime; 
    delaytime = random(); 
    for (i = 0; i<delaytime; i++); 
} 

void *woman(void *param) 
{ 
    sem_wait(&z); 
     sem_wait(&wsem); 
      sem_wait(&y); 
       wcount++; 
       if(wcount==1) 
       { sem_wait(&msem); } 
      sem_post(&y); 
     sem_post(&wsem); 
    sem_post(&z); 

    sem_wait(&cap); 

    printf("woman in!\n"); 
    delay(); 
    printf("\twoman out!\n"); 

    sem_post(&cap);  

    sem_wait(&y); 
     wcount--; 
     if(wcount==0) 
     { sem_post(&msem); } 
    sem_post(&y); 
} 

void *man(void *param) 
{   
    sem_wait(&z); 
     sem_wait(&msem); 
      sem_wait(&x); 
       mcount++; 
       if(mcount==1) 
       { sem_wait(&wsem); } 
      sem_post(&x); 
     sem_post(&msem); 
    sem_post(&z); 

    sem_wait(&cap); 

    printf("\t\tman in!\n"); 
    delay(); 
    printf("\t\t\tman out!\n"); 

    sem_post(&cap); 

    sem_wait(&x); 
     mcount--; 
     if(mcount==0) 
     {sem_post(&wsem);} 
    sem_post(&x); 
} 

int main(void) 
{ 
    int i; 
    srandom(60); 

     mcount = 0; 
     wcount = 0; 
     sem_init(&x,0,1); // for sem_init, initial value is 3rd argument 
     sem_init(&y,0,1); 
     sem_init(&z,0,1); 
     sem_init(&wsem,0,1); 
     sem_init(&msem,0,1); 
     sem_init(&cap,0,4); // eg. cap initialized to 4 

     pthread_t *tid; 
     tid = malloc(80*sizeof(pthread_t)); 

    // You can use your cobegin statement here, instead of pthread_create()  
    // I have forgone the use of pthread barriers although I suppose they would nicely imitate the functionality of cobegin. 
    // This is merely to retain simplicity. 

    for(i=0;i<10;i++) 
    { 
     pthread_create(&tid[i],NULL,woman,NULL); 
    } 
    for(i=10;i<20;i++) 
    {  
      pthread_create(&tid[i],NULL,man,NULL); 
    } 
    for(i=0;i<20;i++) 
    {  
      pthread_join(tid[i],NULL); 
    } 

    return(0); 
} 

Mientras se convierte en el formulario 2-sanos, tome nota de las variables del contador de semáforos & que deberá duplicar para satisfacer todas las condiciones. Feliz semaforing!

0

para el código Baci 4 baño:

const int Delayx = 60; 
    int i; 
    int Mcount,Wcount; 
    binarysem x,y,z,Wsem,Msem; 
    semaphore cap; 
    void Delay(void) 
    { 
    int DelayTime; 
    DelayTime = random(Delayx); 
    for (i = 0; i<DelayTime; i++); 
    } 

void Woman(void) 
    { 
    wait(z); 
    wait(Wsem); 
    wait(y); 
    Wcount++; 
    if(Wcount==1) 
     { wait(Msem); } 
     signal(y); 
     signal(Wsem); 
     signal(z); 

     wait(cap); 
     cout << "A Woman has entered Restroom"<<endl; 
     Delay(); 
     cout << "A Woman has exited Restroom"<<endl; 

     signal(cap); 
     wait(y); 
     Wcount--; 
     if(Wcount==0) 
     {signal(Msem);} 

     signal(y); 
     } 

void Man(void) 
    { 
    wait(z); 
    wait(Msem); 
    wait(x); 
    Mcount++; 
    if(Mcount==1) 
     { wait(Wsem); } 
     signal(x); 
     signal(Msem); 
     signal(z); 

     wait(cap); 
     cout << "A Man has entered Restroom"<<endl; 
     Delay(); 
     cout << "A Man has exited Restroom"<<endl; 

     signal(cap); 
     wait(x); 
     Mcount--; 
     if(Mcount==0) 
     {signal(Wsem);} 

     signal(x); 
     } 


void main() 
{ 
Mcount=0; 
Wcount=0; 
initialsem(x,1); 
initialsem(y,1); 
initialsem(z,1); 
initialsem(Wsem,1); 
initialsem(Msem,1); 
initialsem(cap,4); 
cobegin 
{ 
    Woman(); Woman(); Woman(); 
    Woman(); Woman(); Woman(); 
    Woman(); 
    Woman(); Man(); Man(); 
    Man(); Man(); Man(); Man(); 
    Man(); Man(); 
} 
     } 
Cuestiones relacionadas