Advertisement
Guest User

Untitled

a guest
Oct 25th, 2014
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.76 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <time.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5.  
  6. #define N 5
  7. #define LEFT ((i+N-1)%N)
  8. #define RIGHT ((i+1)%N)
  9. #define THINKING 0
  10. #define HUNGRY 1
  11. #define EATING 2
  12.  
  13. int state[N];
  14. int phil[N] = {0,1,2,3,4};
  15. pthread_mutex_t the_mutex;
  16. pthread_mutex_t s[N];
  17.  
  18. void eat(int i)
  19. {  
  20.     if ( state[i] == EATING )
  21.         printf("Philosopher %d is eating with fork %d and %d\n", i, LEFT, RIGHT);
  22.     //usleep(100000);
  23. }
  24.  
  25. void think(int i)
  26. {
  27.     if ( state[i] == THINKING )
  28.         printf("Philosopher %d is thinking\n", i);
  29.     //usleep(10000);
  30. }
  31.  
  32. void hungry(int i)
  33. {
  34.     if ( state[i] == HUNGRY )
  35.         printf("Philosopher %d is hungry\n", i);
  36. }
  37.  
  38. void test(int i)
  39. {
  40.     if (state[i] == HUNGRY && state[LEFT] != EATING
  41.         && state[RIGHT] != EATING)
  42.     {
  43.         state[i] = EATING;
  44.         eat(i);
  45.         pthread_mutex_unlock(&s[i]);
  46.     }
  47. }
  48.  
  49. void takefork(int i)
  50. {
  51.     pthread_mutex_lock(&the_mutex);
  52.     state[i] = HUNGRY;
  53.     hungry(i);
  54.     test(i);
  55.     pthread_mutex_unlock(&the_mutex);
  56.     pthread_mutex_lock(&s[i]);
  57. }
  58.  
  59. void putfork(int i)
  60. {
  61.     pthread_mutex_lock(&the_mutex);
  62.     state[i] = THINKING;
  63.     test(LEFT);
  64.     test(RIGHT);
  65.     pthread_mutex_unlock(&the_mutex);
  66. }
  67.  
  68. void *philosopher(void * num)
  69. {
  70.     int i = (int)num;
  71.     while (1)
  72.     {  
  73.         think(i);      
  74.         takefork(i); //critical region start
  75.         eat(i);
  76.         putfork(i); //critical region end
  77.     }
  78. }
  79.  
  80. int main()
  81. {
  82.     int i;
  83.     pthread_t phil_id[N];
  84.     pthread_mutex_init(&the_mutex, 0);
  85.    
  86.     for (i= 0; i < N; i++)
  87.     {
  88.         pthread_mutex_init(&s[i], 0);
  89.     }  
  90.    
  91.     for (i= 0; i < N; i++)
  92.     {
  93.         pthread_create(&phil_id[i], 0, philosopher, (void*)phil[i]);
  94.     }
  95.  
  96.     for (i = 0; i > -1; i--)
  97.     {
  98.         pthread_join(phil[i], NULL);
  99.     }
  100.    
  101.     pthread_mutex_destroy(&the_mutex);
  102.     for (i = 0; i < N; i++)
  103.     {  
  104.         pthread_mutex_destroy(&s[i]);
  105.     }
  106.    
  107.    
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement