Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <semaphore.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <thread>
- using namespace std;
- sem_t p[5]; //Declaracion de un array de semaforos
- sem_t sitios; //Declaracion de una variable de semaforos
- void filosofo(int n_filosofo)
- {
- /*printf("\nFilosofo [%d] esta pensando",n_filosofo,"\n");*/ cout<<"\nFilosofo ["<<(n_filosofo+1)<<"] esta pensando"<<endl;
- sem_wait(&sitios);
- sem_wait(&p[n_filosofo]);
- sem_wait(&p[(n_filosofo+1)%5]);
- /*printf("\nFilosofo [%d] esta comiendo",n_filosofo);*/ cout<<"\nFilosofo ["<<(n_filosofo+1)<<"] esta comiendo"<<endl;
- sem_post(&p[n_filosofo]);
- sem_post(&p[(n_filosofo+1)%5]);
- sem_post(&sitios);
- cout<<"\nFilosofo ["<<(n_filosofo+1)<<"] deja de comer"<<endl;
- }
- int main()
- {
- thread hilo[4];
- sem_init(&sitios,0,4);
- for(int i=0;i<4;i++)
- {
- sem_init(&p[i],1,1);
- }
- for(int i=0;i<4;i++)
- {
- hilo[i] = thread(filosofo,i);
- }
- for(int i=0;i<4;i++)
- {
- hilo[i].join();
- }
- system("PAUSE");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement