Advertisement
Guest User

philosophers

a guest
Oct 27th, 2012
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<semaphore.h>
  3. #include<pthread.h>
  4.  
  5. #define N 5
  6. #define THINKING 0
  7. #define HUNGRY 1
  8. #define EATING 2
  9. #define LEFT (ph_num+4)%N
  10. #define RIGHT (ph_num+1)%N
  11.  
  12. sem_t mutex;
  13. sem_t S[N];
  14.  
  15. void * philospher(void *num);
  16. void take_fork(int);
  17. void put_fork(int);
  18. void test(int);
  19.  
  20. int state[N];
  21. int phil_num[N]={0,1,2,3,4}, feast =0;
  22.  
  23. int main()
  24. {
  25.     int i;
  26.     pthread_t thread_id[N];
  27.     sem_init(&mutex,0,1);
  28.     for(i=0;i<N;i++)
  29.         sem_init(&S[i],0,0);
  30.     for(i=0;i<N;i++)
  31.     {
  32.         pthread_create(&thread_id[i],NULL,philospher,&phil_num[i]);
  33.         printf("Philosopher %d is thinking\n",i+1);
  34.     }
  35.     for(i=0;i<N;i++)
  36.         pthread_join(thread_id[i],NULL);
  37.        
  38.     return 0;
  39. }
  40.  
  41. void *philospher(void *num)
  42. {
  43.     int j=0;
  44.     while(j < 10)
  45.     {
  46.         int *i = num;
  47.         sleep(1);
  48.         take_fork(*i);
  49.         sleep(0);
  50.         put_fork(*i);
  51.        
  52.     }
  53. }
  54.  
  55. void take_fork(int ph_num)
  56. {
  57.     sem_wait(&mutex);
  58.     state[ph_num] = HUNGRY;
  59.     printf("Philosopher %d is Hungry\n",ph_num+1);
  60.     test(ph_num);
  61.     sem_post(&mutex);
  62.     sem_wait(&S[ph_num]);
  63.     sleep(1);
  64. }
  65.  
  66. void test(int ph_num)
  67. {
  68.     if (state[ph_num] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING)
  69.     {
  70.         state[ph_num] = EATING;
  71.         sleep(2);
  72.         printf("Philosopher %d takes fork %d and %d\n",ph_num+1,LEFT+1,ph_num+1);
  73.         printf("Philosopher %d is Eating\n",ph_num+1);
  74.         sem_post(&S[ph_num]);
  75.     }
  76. }
  77.  
  78. void put_fork(int ph_num)
  79. {
  80.     sem_wait(&mutex);
  81.     test(LEFT);
  82.     test(RIGHT);
  83.         state[ph_num] = THINKING;
  84.     printf("Philosopher %d putting fork %d and %d down\n",ph_num+1,LEFT+1,ph_num+1);
  85.     printf("Philosopher %d is thinking\n",ph_num+1);
  86.     sem_post(&mutex);
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement