Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.83 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <semaphore.h>
  4. #include <pthread.h>
  5. #define N 5
  6. sem_t tenedor[N];
  7.  
  8. void *filosofo(void *filo){
  9.     int f;
  10.     f = *((int *) filo);
  11.     while(1){
  12.         printf("Voy a pensar: %d\n", f);
  13.         printf("Espero por primer Tenedor: %d\n", f);
  14.         sem_wait(&tenedor[f]);
  15.         printf("Espero por segundo Tenedor: %d\n", f);
  16.         sem_wait(&tenedor[(f+1)%N]);
  17.         printf("Voy a comer: %d\n", f);
  18.         sem_post(&tenedor[f]);
  19.         sem_post(&tenedor[(f+1)%N]);
  20.     }
  21.     pthread_exit(EXIT_SUCCESS);
  22. }
  23.  
  24. int main(){
  25.     int i[N] = {0,1,2,3,4}, j;
  26.     pthread_t f[N];
  27.     for (j = 0; j<N;j++){ sem_init(&tenedor[j], 0 , 1); }
  28.     for (j = 0; j<N;j++){ pthread_create(&f[j], NULL, filosofo, (void*) &i[j]); }
  29.     for (j = 0; j<N;j++){ pthread_join(f[j], NULL); }
  30.     for (j = 0; j<N;j++){ sem_destroy(&tenedor[j]); }
  31.     exit(EXIT_SUCCESS);
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement