samkopite

Untitled

Sep 18th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 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};
  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 thinkingn",i+1);
  34. }
  35. for(i=0;i<N;i++)
  36. pthread_join(thread_id[i],NULL);
  37. }
  38.  
  39. void *philospher(void *num)
  40. {
  41. while(1)
  42. {
  43. int *i = num;
  44. sleep(1);
  45. take_fork(*i);
  46. sleep(0);
  47. put_fork(*i);
  48. }
  49. }
  50.  
  51. void take_fork(int ph_num)
  52. {
  53. sem_wait(&mutex);
  54. state[ph_num] = HUNGRY;
  55. printf("Philosopher %d is Hungryn",ph_num+1);
  56. test(ph_num);
  57. sem_post(&mutex);
  58. sem_wait(&S[ph_num]);
  59. sleep(1);
  60. }
  61.  
  62. void test(int ph_num)
  63. {
  64. if (state[ph_num] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING)
  65. {
  66. state[ph_num] = EATING;
  67. sleep(2);
  68. printf("Philosopher %d takes fork %d and %dn",ph_num+1,LEFT+1,ph_num+1);
  69. printf("Philosopher %d is Eatingn",ph_num+1);
  70. sem_post(&S[ph_num]);
  71. }
  72. }
  73.  
  74. void put_fork(int ph_num)
  75. {
  76. sem_wait(&mutex);
  77. state[ph_num] = THINKING;
  78. printf("Philosopher %d putting fork %d and %d downn",ph_num+1,LEFT+1,ph_num+1);
  79. printf("Philosopher %d is thinkingn",ph_num+1);
  80. test(LEFT);
  81. test(RIGHT);
  82. sem_post(&mutex);
  83. }
Add Comment
Please, Sign In to add comment