Dining Philosophers Problem between Processes
This is a solution to Dining Philosophers Problem between Processes. It starts 5 processes that runs infinitely, so require at least Intel i3 processor.
Platform : Linux
#include<iostream>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/mman.h>
#include<fcntl.h>
#include<unistd.h>
#include<semaphore.h>
using namespace std;
#define FORKS 5
#define PHIL_NUM 5
#define SNAME "SEM"
key_t key = 5678;
class philosopher {
sem_t *lock;
int shmid, *s, *shm, n, left_fork, right_fork;
void open_sem();
void open_shm(int);
void think (void);
void eat (void);
void take_forks ();
void put_forks ();
public:
const static int INIT = 0, NORMAL = 1;
philosopher(int );
void init_shm();
void start();
};
/* initialises shared memory all positions to 0*/
void philosopher :: init_shm () {
open_shm (INIT);
}
/** opens shared memory for a process at normal mode **/
void philosopher :: open_shm(int mode) {
if ((shmid = shmget(key, FORKS * sizeof(int), IPC_CREAT | 0666)) < 0) {
cout<<"shmget";
exit(1);
}
if ( * (shm = (int *)shmat(shmid, NULL, 0)) == -1) {
cout<<"shmat";
exit(1);
}
s = shm;
if (mode == INIT) {
for(int i = 0; i < PHIL_NUM; i++) {
*s++ = 0;
}
}
}
/** opening shared semaphores **/
void philosopher :: open_sem() {
lock = sem_open(SNAME, O_CREAT, 0644);
sem_init(lock, 1, 1);
}
void philosopher::think() {
cout<<"Philosopher "<<n<<" Starts thinking.\n";
sleep(2);
take_forks();
}
void philosopher::eat() {
cout<<"Philosopher "<<n<<" Starts eating.\n";
sleep(2);
put_forks();
}
void philosopher::take_forks() {
sem_wait(lock);
while(!(s[left_fork] == 0 && s[right_fork] == 0)) {
}
s[right_fork] = 1;
s[left_fork] = 1;
sem_post(lock);
eat();
}
void philosopher::put_forks() {
s[right_fork] = 0;
s[left_fork] = 0;
think();
}
philosopher::philosopher(int num) {
this->n = num;
this->left_fork = num;
this->right_fork = (num + 1) % PHIL_NUM;
open_shm(NORMAL);
open_sem();
}
void philosopher :: start() {
take_forks();
}
int main() {
/** Initialize the shared memories to 0 - means forks free **/
philosopher p(2);
p.init_shm();
/** Create dynamic philosophers **/
for(int i = 0; i < PHIL_NUM; i++)
if(fork() == 0) {
philosopher *p = new philosopher(i);
p -> start();
exit(0);
}
sleep(10);
return 0;
}
Comments
Post a Comment