Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <dirent.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <pwd.h>
  6. #include <fcntl.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <sys/sem.h>
  10. #include <assert.h>
  11. #include <time.h>
  12. #define N 5
  13. #define LEFT (i - 1) % N
  14. #define RIGHT (i + 1) % N
  15.  
  16. #define THINKING 0
  17. #define HUNGRY 1
  18. #define EATING 2
  19. #define MAX_TIME 5
  20. int key1, key2;
  21. typedef int semaphore;
  22. int state[N];
  23. semaphore mutex = 1;
  24. semaphore s[N];
  25.  
  26. void down(int semdec)
  27. {
  28. struct sembuf semd;
  29. semd.sem_num = 0;
  30. semd.sem_op = -1;
  31. semd.sem_flg = 0;
  32. semop(semdec, &semd, 1);
  33. }
  34.  
  35. void up(int semdec)
  36. {
  37. struct sembuf semd;
  38. semd.sem_num = 0;
  39. semd.sem_op = 1;
  40. semd.sem_flg = 0;
  41. semop(semdec, &semd, 1);
  42. }
  43.  
  44.  
  45. void Test(int i){
  46. if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING){
  47. state[i] = EATING;
  48. up(&s[i]);
  49. }
  50. }
  51.  
  52.  
  53. void TakesForks(int i){
  54. down(&mutex);
  55. state[i] = HUNGRY;
  56. Test(i);
  57. up(&mutex);
  58. down(&s[i]);
  59. printf("%d ", i);
  60. printf("КУШАЕТ\n");
  61. fflush(stdout);
  62. }
  63.  
  64. void PutForks(int i){
  65. down(&mutex);
  66. state[i] = THINKING;
  67. Test(LEFT);
  68. Test(RIGHT);
  69. up(&mutex);
  70. printf("%d ", i);
  71. printf("ЧИЛЛИТ\n");
  72. fflush(stdout);
  73. }
  74.  
  75.  
  76. void philosopher(int i){
  77. while(1){
  78. int th_time = rand() % MAX_TIME;
  79. sleep(th_time); //размышления
  80. TakesForks(i);
  81. int eat_time = rand() % MAX_TIME;
  82. sleep(eat_time); //кушает
  83. PutForks(i);
  84. }
  85. }
  86.  
  87.  
  88.  
  89. int main(){
  90. key1 = ftok("./6tsk.c", 'S');
  91. int mutex = semget(key1, 0, 0);
  92. key2 = ftok("./6tsk.c", 'S');
  93. int s = semget(key2, 2, 0);
  94. if(fork() == 0){
  95. philosopher(1);
  96. }
  97. if(fork() == 0){
  98. philosopher(2);
  99. }
  100. if(fork() == 0){
  101. philosopher(3);
  102. }
  103. if(fork() == 0){
  104. philosopher(4);
  105. }
  106. if(fork() == 0){
  107. philosopher(5);
  108. }
  109. char c;
  110. if (c = getchar() == EOF){
  111. return 0;
  112. }
  113. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement