Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<semaphore.h>
- #include<pthread.h>
- //Number of Philosophers
- #define M 5
- //Think
- #define THINK 0
- //Hungry
- #define HUNGRY 1
- //Eat
- #define EAT 2
- //Left chopstick
- #define LEFTCHOP (phNum+4)%M
- //Right chopstick
- #define RIGHTCHOP (phNum+1)%M
- //Semaphore variables
- sem_t ourMutex;
- sem_t S[M];
- //Declare the needed methods
- void* diningPhilospher(void* number);
- void takeFork(int);
- void putFork(int);
- void tester(int);
- //Declare the needed array
- int state[M];
- int philNum[M] = { 0,1,2,3,4 };
- //Driver
- int main()
- {
- //Declare the needed variable
- int j;
- //Declare a thread
- pthread_t threadID[M];
- //Initialize
- sem_init(&ourMutex, 0, 1);
- //Loop
- for (j = 0;j < M;j++)
- //Initialize
- sem_init(&S[j], 0, 0);
- //Loop
- for (j = 0;j < M;j++)
- {
- //Create thread
- pthread_create(&threadID[j], NULL, diningPhilospher, &philNum[j]);
- //Display message
- printf("Philosopher %d is thinking\n", j + 1);
- }
- //Loop
- for (j = 0;j < M;j++)
- //Thread
- pthread_join(threadID[j], NULL);
- }
- //Method definition diningPhilospher()
- void* diningPhilospher(void* number)
- {
- //Loop
- while (1)
- {
- //Initialize
- int* j = number;
- //Function call
- takeFork(*j);
- //Function call
- putFork(*j);
- }
- }
- //Method definition
- void takeFork(int phNum)
- {
- //Wait
- sem_wait(&ourMutex);
- //Update state
- state[phNum] = HUNGRY;
- //Display
- printf("Philosopher %d is Hungry\n", phNum + 1);
- //Function call
- tester(phNum);
- sem_post(&ourMutex);
- //Wait
- sem_wait(&S[phNum]);
- }
- //Method definition
- void tester(int phNum)
- {
- //Condition check
- if (state[phNum] == HUNGRY && state[LEFTCHOP] != EAT && state[RIGHTCHOP] != EAT)
- {
- //State
- state[phNum] = EAT;
- //Display
- printf("Philosopher %d takes fork %d and %d\n", phNum + 1, LEFTCHOP + 1, phNum + 1);
- //Display
- printf("Philosopher %d is Eating\n", phNum + 1);
- sem_post(&S[phNum]);
- }
- }
- //Method definition
- void putFork(int phNum)
- {
- //Wait
- sem_wait(&ourMutex);
- //State
- state[phNum] = THINK;
- //Display
- printf("Philosopher %d putting fork %d and %d down\n", phNum + 1, LEFTCHOP + 1, phNum + 1);
- //Display
- printf("Philosopher %d is thinking\n", phNum + 1);
- //Function call
- tester(LEFTCHOP);
- //Function call
- tester(RIGHTCHOP);
- sem_post(&ourMutex);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement