Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <sys/types.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <limits.h>
- #include <errno.h>
- #include <string.h>
- #include <time.h>
- typedef int semaphore;
- int th[] = {2, 3, 5, 4, 7}, state[5], et[] = {5, 3, 4, 5, 1};
- semaphore p[5], mutex = 1;
- enum {
- THINKING,
- HUNGRY,
- EATING,
- LEFT = (i - 1) % 5,
- RIGHT = (i + 1) % 5
- }
- void
- think(int i)
- {
- printf("PH#%d started thinking\n", i);
- sleep(th[i]);
- printf("PH#%d stopped thinking\n", i);
- return 0;
- }
- void
- eat(int i)
- {
- printf("PH#%d started eating\n", i);
- sleep(et[i]);
- printf("PH#%d stopped eating\n", i);
- return 0;
- }
- void
- test(int i)
- {
- if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) {
- state[i] = EATING;
- up(&p[i]);
- }
- }
- void
- take_forks(int i)
- {
- down(&mutex);
- state[i] = HUNGRY;
- test(i);
- up(&mutex);
- down(p[i]);
- }
- void
- put_forks(int i)
- {
- down(&mutex);
- state[i] = THINKING;
- test(LEFT);
- test(RIGHT);
- up(&mutex);
- }
- void
- philosopher(int i, int lim)
- {
- for (int j = 0; j < lim; ++j) {
- think(i);
- take_forks(i);
- eat(i);
- put_forks(i);
- }
- printf("PH#%d left the chat\n", i);
- }
- int
- main(int argc, char *argv[])
- {
- for (int i = 0; i < 5; ++i) {
- if (!fork()) {
- philosopher(i);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement