jfcmacro

fumadores.cpp

Mar 21st, 2019
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #include <iostream>
  2. #include <pthread.h>
  3. #include <cstdlib>
  4. #include <semaphore.h>
  5.  
  6. using namespace std;
  7.  
  8. struct FumadorInfo {
  9.   sem_t *evento, *semagente;
  10.   const char *msg;
  11.   FumadorInfo(sem_t *evento,
  12.           sem_t *semagente,
  13.           const char *msg) :
  14.     evento(evento),
  15.     semagente(semagente),
  16.     msg(msg) { }
  17. };
  18.  
  19. enum SEMID { NOTABACO, NOPAPEL, NOCERILLA, AGENTE };
  20. const char *msg[] = { "Fumador con tabaco",
  21.               "Fumador con papel",
  22.               "Fumador con cerilla",
  23.               "Agente" };
  24.  
  25. const int nSem = 4;
  26.  
  27. struct AgenteInfo {
  28.   sem_t *semaforos;
  29.   AgenteInfo(sem_t *semaforos) :
  30.     semaforos(semaforos) { }
  31. };
  32.  
  33. void* fumador(void *);
  34. void* agente(void*);
  35.  
  36. int
  37. main() {
  38.   sem_t semaforos[nSem];
  39.   pthread_t hilos[nSem];
  40.  
  41.   for (int i = 0; i < nSem; i++) {
  42.     sem_init(&semaforos[i], 0, 0);
  43.   }
  44.  
  45.   for (int i = 0; i < nSem - 1; i++) {
  46.     FumadorInfo* inf = new FumadorInfo(&semaforos[i],
  47.                        &semaforos[nSem- 1],
  48.                        msg[i]);
  49.     pthread_create(&hilos[i], NULL,
  50.            fumador, (void *) inf);
  51.   }
  52.  
  53.   AgenteInfo *ai = new AgenteInfo(semaforos);
  54.  
  55.   pthread_create(&hilos[nSem-1], NULL,
  56.          agente, (void*) ai);
  57.  
  58.   for (int i = 0; i < nSem; ++i) {
  59.     pthread_join(hilos[i],NULL);
  60.   }
  61.  
  62.   return EXIT_SUCCESS;
  63. }
  64.  
  65. void*
  66. fumador(void *arg) {
  67.   FumadorInfo *pInfo = (FumadorInfo*) arg;
  68.  
  69.   for (;;) {
  70.     sem_wait(pInfo->evento);
  71.     cout << pInfo->msg << endl;
  72.     sem_post(pInfo->semagente);
  73.   }
  74. }
  75.  
  76. void*
  77. agente(void *arg) {
  78.   AgenteInfo * pInfo = (AgenteInfo*) arg;
  79.  
  80.   for (;;) {
  81.     switch(rand() % 3) {
  82.     case NOTABACO:
  83.       sem_post(&pInfo->semaforos[NOTABACO]);
  84.       break;
  85.     case NOPAPEL:
  86.       sem_post(&pInfo->semaforos[NOPAPEL]);
  87.       break;
  88.     case NOCERILLA:
  89.       sem_post(&pInfo->semaforos[NOCERILLA]);
  90.       break;
  91.     }
  92.     cout << msg[AGENTE] << endl;
  93.     sem_wait(&pInfo->semaforos[AGENTE]);
  94.   }
  95. }
Advertisement
Add Comment
Please, Sign In to add comment