Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <pthread.h>
- #include <cstdlib>
- #include <semaphore.h>
- using namespace std;
- struct FumadorInfo {
- sem_t *evento, *semagente;
- const char *msg;
- FumadorInfo(sem_t *evento,
- sem_t *semagente,
- const char *msg) :
- evento(evento),
- semagente(semagente),
- msg(msg) { }
- };
- enum SEMID { NOTABACO, NOPAPEL, NOCERILLA, AGENTE };
- const char *msg[] = { "Fumador con tabaco",
- "Fumador con papel",
- "Fumador con cerilla",
- "Agente" };
- const int nSem = 4;
- struct AgenteInfo {
- sem_t *semaforos;
- AgenteInfo(sem_t *semaforos) :
- semaforos(semaforos) { }
- };
- void* fumador(void *);
- void* agente(void*);
- int
- main() {
- sem_t semaforos[nSem];
- pthread_t hilos[nSem];
- for (int i = 0; i < nSem; i++) {
- sem_init(&semaforos[i], 0, 0);
- }
- for (int i = 0; i < nSem - 1; i++) {
- FumadorInfo* inf = new FumadorInfo(&semaforos[i],
- &semaforos[nSem- 1],
- msg[i]);
- pthread_create(&hilos[i], NULL,
- fumador, (void *) inf);
- }
- AgenteInfo *ai = new AgenteInfo(semaforos);
- pthread_create(&hilos[nSem-1], NULL,
- agente, (void*) ai);
- for (int i = 0; i < nSem; ++i) {
- pthread_join(hilos[i],NULL);
- }
- return EXIT_SUCCESS;
- }
- void*
- fumador(void *arg) {
- FumadorInfo *pInfo = (FumadorInfo*) arg;
- for (;;) {
- sem_wait(pInfo->evento);
- cout << pInfo->msg << endl;
- sem_post(pInfo->semagente);
- }
- }
- void*
- agente(void *arg) {
- AgenteInfo * pInfo = (AgenteInfo*) arg;
- for (;;) {
- switch(rand() % 3) {
- case NOTABACO:
- sem_post(&pInfo->semaforos[NOTABACO]);
- break;
- case NOPAPEL:
- sem_post(&pInfo->semaforos[NOPAPEL]);
- break;
- case NOCERILLA:
- sem_post(&pInfo->semaforos[NOCERILLA]);
- break;
- }
- cout << msg[AGENTE] << endl;
- sem_wait(&pInfo->semaforos[AGENTE]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment