Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4. #include <sys/types.h>
  5. #include <fcntl.h>
  6. #include <stdlib.h>
  7. #include <limits.h>
  8. #include <errno.h>
  9. #include <string.h>
  10. #include <time.h>
  11.  
  12. typedef int semaphore;
  13.  
  14. int th[] = {2, 3, 5, 4, 7}, state[5], et[] = {5, 3, 4, 5, 1};
  15. semaphore p[5], mutex = 1;
  16. enum {
  17. THINKING,
  18. HUNGRY,
  19. EATING,
  20. LEFT = (i - 1) % 5,
  21. RIGHT = (i + 1) % 5
  22. }
  23.  
  24. void
  25. think(int i)
  26. {
  27. printf("PH#%d started thinking\n", i);
  28. sleep(th[i]);
  29. printf("PH#%d stopped thinking\n", i);
  30. return 0;
  31. }
  32.  
  33. void
  34. eat(int i)
  35. {
  36. printf("PH#%d started eating\n", i);
  37. sleep(et[i]);
  38. printf("PH#%d stopped eating\n", i);
  39. return 0;
  40. }
  41.  
  42. void
  43. test(int i)
  44. {
  45. if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) {
  46. state[i] = EATING;
  47. up(&p[i]);
  48. }
  49. }
  50.  
  51. void
  52. take_forks(int i)
  53. {
  54. down(&mutex);
  55. state[i] = HUNGRY;
  56. test(i);
  57. up(&mutex);
  58. down(p[i]);
  59. }
  60.  
  61. void
  62. put_forks(int i)
  63. {
  64. down(&mutex);
  65. state[i] = THINKING;
  66. test(LEFT);
  67. test(RIGHT);
  68. up(&mutex);
  69. }
  70.  
  71. void
  72. philosopher(int i, int lim)
  73. {
  74. for (int j = 0; j < lim; ++j) {
  75. think(i);
  76. take_forks(i);
  77. eat(i);
  78. put_forks(i);
  79. }
  80. printf("PH#%d left the chat\n", i);
  81. }
  82.  
  83.  
  84.  
  85.  
  86. int
  87. main(int argc, char *argv[])
  88. {
  89. for (int i = 0; i < 5; ++i) {
  90. if (!fork()) {
  91. philosopher(i);
  92. }
  93. }
  94.  
  95. return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement