哲学家问题是操作系统中资源分配的经典问题
linux平台下的系统api不同于Windows下的实现
要求:一个正确的哲学家程序(不会发生死锁)
一个错误的哲学家程序(会发生死锁)
系统环境:ElementaryOS
wrong.c
#include<stdio.h> #include<stdlib.h> #include<sys/ipc.h> #include<sys/msg.h> #include<sys/types.h> #include<unistd.h> #include<errno.h> #include<sys/ipc.h> #include<sys/sem.h> #include<sys/wait.h> #define DELAY (rand() % 5 + 1) #define ERR_EXIT(m) do { perror(m); exit(EXIT_FAILURE); } while(0) union semun { int val; // Value for SETVAL struct semid_ds *buf; //Buffer for IPC_STAT, IPC_SET unsigned short *array; /* Array for GETALL, SETALL */ struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ }; //semid ! this is the number of share memory int semid; //waiting for fork here //left and right = the number of sourses void wait_for_1fork(int no) { int left = no; //system defined struct //"first":the current number of pro //"second":resourses -1:wait cannot use;+1:can use //"thired":? struct sembuf buf[1] = { {left, -1, 0}, }; //semop do wait or signal (p/v) //"first": the number of share memory pro //"second":the first point of struct //"third":the number of signal to complete semop(semid, buf, 1); } void wait_for_2fork(int no) { int right = (no + 1) % 5; //system defined struct //"first":the current number of pro //"second":resourses -1:wait cannot use;+1:can use //"thired":? struct sembuf buf[1] = { {right, -1, 0} }; //semop do wait or signal (p/v) //"first": the number of share memory pro //"second":the first point of struct //"third":the number of signal to complete semop(semid, buf, 1); } void free_1fork(int no) { int left = no; //system defined struct //"first":the current number of pro //"second":resourses -1:wait cannot use;+1:can use //"thired":? struct sembuf buf[1] = { {left, 1, 0}, }; semop(semid, buf, 1); } void free_2fork(int no) { int right = (no + 1) % 5; //system defined struct //"first":the current number of pro //"second":resourses -1:wait cannot use;+1:can use //"thired":? struct sembuf buf[1] = { {right, 1, 0} }; semop(semid, buf, 1); } void philosopere(int num) { srand(getpid()); for (; ;) { //printf("%d is thinking ", num); printf("