Advertisement
Guest User

Untitled

a guest
May 28th, 2015
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/wait.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <stdlib.h>
  6. #include <pthread.h>
  7. #include <semaphore.h>
  8.  
  9. #define THINKING 0
  10. #define HUNGRY 1
  11. #define EATING 2
  12. #define LEFT (i-1)%N
  13. #define RIGHT (i+1)%N
  14.  
  15. typedef int semaphore;
  16. int N=5;
  17. int status [5];
  18. semaphore mutex = 1;
  19. semaphore s[5];
  20.  
  21. void PrintStatus()
  22. {
  23. int i;
  24. for (i=0; i<N; i++)
  25. printf ("Состояние ",i, " философа - ", status[i]);
  26. }
  27.  
  28. void Test(int i)
  29. {
  30. if(status[i]==HUNGRY && status[LEFT]!=EATING && status[RIGHT]!=EATING)
  31. {
  32. status[i] = EATING;
  33. up(&s[i]);
  34. }
  35. }
  36.  
  37. void TakeForks(int i)
  38. {
  39. down(&mutex);
  40. status[i] = HUNGRY;
  41. PrintStatus();
  42. Test(i);
  43. up(&mutex);
  44. down(&s[i]);
  45. }
  46.  
  47. void PutForks(int i)
  48. {
  49. down(&mutex);
  50. status[i] = THINKING;
  51. PrintStatus();
  52. Test(LEFT);
  53. Test(RIGHT);
  54. up(&mutex);
  55. }
  56.  
  57. void Eat (int i)
  58. {
  59. printf ("Философ ", i, " ест.");
  60. }
  61.  
  62. void Philosopher(void* j)
  63. {
  64. int i = *(int*)j;
  65. int k = 0;
  66. while(k<10)
  67. {
  68. TakeForks(i);
  69. Eat(i);
  70. PutForks(i);
  71. k++;
  72. }
  73.  
  74. }
  75.  
  76. int main ()
  77. {
  78. pthread_t thread[N];
  79. int i, ithread;
  80. for (i=0; i<N; i++)
  81. status[i] = THINKING;
  82. for (i=0; i<N; i++)
  83. {
  84. ithread = pthread_create (&thread[i], NULL, (void *(*)(void *))Philosopher, &i);
  85. if (ithread != 0)
  86. {
  87. printf ("Error 2");
  88. return 1;
  89. }
  90. }
  91. for (i=0; i<N; i++)
  92. {
  93. ithread = pthread_join(thread[i], NULL);
  94. if (ithread != 0)
  95. {
  96. printf ("Error 3");
  97. return 1;
  98. }
  99. }
  100. return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement