Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdbool.h>
- int forks[5][2]; // Each fork near one philosopher
- bool P[5]; // Philosophers done or not
- int check_right(int pid) {
- if(forks[pid % 5][0] == 0)
- return 1;
- else
- return 0;
- }
- int check_left(int pid) {
- if(forks[((pid - 2) + 5) % 5][1] == 0)
- return 1;
- else
- return 0;
- }
- void take_right(int pid, int done_or_not) {
- if(done_or_not == 1) {
- //printf("P%i is done\n", pid);
- }
- else if(check_right(pid)) {
- forks[pid - 1][1] = 1;
- }
- else {
- //printf("P%i can't take the right one\n", pid);
- }
- }
- void take_left(int pid, int done_or_not) {
- if(done_or_not == 1) {
- //printf("P%i is done\n", pid);
- }
- else if(check_left(pid)) {
- forks[pid - 1][0] = 1;
- }
- else {
- //printf("P%i can't take the left one\n", pid);
- }
- }
- int take_fork(int pid, int done_or_not, const char direction[]) {
- if(!strcmp(direction, "left")) {
- take_left(pid, done_or_not);
- return 1;
- }
- else if(!strcmp(direction, "right")) {
- take_right(pid, done_or_not);
- return 0;
- }
- }
- int main() {
- int i = 0, i2 = 0, counter = 1, p1, p2, p3, p4, p5;
- const char *direction[2];
- direction[0] = "left";
- direction[1] = "right";
- for(i = 0; i < 5; ++i) {
- for(i2 = 0; i2 < 2; ++i2)
- forks[i][i2] = 0;
- P[i] = 0;
- }
- while(P[0] == 0 || P[1] == 0 || P[2] == 0 || P[3] == 0 || P[4] == 0) {
- printf("---------------- #%i ----------------\n", counter);
- // Argument is which philosopher that should take the right or left fork
- // Change to left or right for different preferences for the philosophers
- p1 = take_fork(1 ,P[0] , "left");
- p2 = take_fork(2 ,P[1] , "left");
- p3 = take_fork(3 ,P[2] , "left");
- p4 = take_fork(4 ,P[3] , "right");
- p5 = take_fork(5 ,P[4] , "right");
- // The opposite of their first try
- take_fork(1 ,P[0] , direction[p1]);
- take_fork(2 ,P[1] , direction[p2]);
- take_fork(3 ,P[2] , direction[p3]);
- take_fork(4 ,P[3] , direction[p4]);
- take_fork(5 ,P[4] , direction[p5]);
- for(i = 0; i < 5; ++i)
- printf("%i P%i %i || ", forks[i][0] , i + 1, forks[i][1]);
- printf("\n\n");
- for(i = 0; i < 5; ++i)
- if(forks[i][0] == 1 && forks[i][1] == 1) {
- printf("P%i can eat and will do so \n", i + 1);
- P[i] = 1;
- // Releases the forks so that they can be used by someone else
- forks[i][0] = forks[i][1] = 0;
- }
- else if(P[i] == 0){
- printf("P%i is starving\n", i + 1);
- }
- printf("\n");
- for(i = 0; i < 5; ++i)
- printf("%i P%i %i || ", forks[i][0] , i + 1, forks[i][1]);
- printf("\n");
- ++counter;
- sleep(5);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement