Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <semaphore.h>
- #include <pthread.h>
- #define N 5
- sem_t tenedor[N];
- void *filosofo(void *filo){
- int f;
- f = *((int *) filo);
- while(1){
- printf("Voy a pensar: %d\n", f);
- printf("Espero por primer Tenedor: %d\n", f);
- sem_wait(&tenedor[f]);
- printf("Espero por segundo Tenedor: %d\n", f);
- sem_wait(&tenedor[(f+1)%N]);
- printf("Voy a comer: %d\n", f);
- sem_post(&tenedor[f]);
- sem_post(&tenedor[(f+1)%N]);
- }
- pthread_exit(EXIT_SUCCESS);
- }
- int main(){
- int i[N] = {0,1,2,3,4}, j;
- pthread_t f[N];
- for (j = 0; j<N;j++){ sem_init(&tenedor[j], 0 , 1); }
- for (j = 0; j<N;j++){ pthread_create(&f[j], NULL, filosofo, (void*) &i[j]); }
- for (j = 0; j<N;j++){ pthread_join(f[j], NULL); }
- for (j = 0; j<N;j++){ sem_destroy(&tenedor[j]); }
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement