Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Created by aqib on 8/9/20.
- //
- #include <bits/stdc++.h>
- #include <pthread.h>
- #include <semaphore.h>
- #include <cstdio>
- #include <unistd.h>
- #include <ctime>
- #define N 5
- #define THINKING 2
- #define HUNGRY 1
- #define EATING 0
- #define LEFT (philosopher_number + 4) % N
- #define RIGHT (philosopher_number + 1) % N
- //int j=0;
- int flag[N] = {0};
- char status[][10] = {"EATING", "HUNGRY", "THINKING"};
- int state[N];
- int phil[N] = {0, 1, 2, 3, 4};
- sem_t mutex;
- sem_t S[N];
- void showStatus() {
- printf("\n");
- for (int k = 0; k < 5; k++) {
- if (flag[k] != 0)
- printf("Philosopher %d is %s \t", k + 1, status[state[k]]);
- }
- printf("\n");
- sleep(3);
- }
- void test(int philosopher_number) {
- if (state[philosopher_number] == HUNGRY
- && state[LEFT] != EATING
- && state[RIGHT] != EATING) {
- // state that eating
- state[philosopher_number] = EATING;
- sleep(2);
- printf("\nPhilosopher %d takes fork %d and %d\n", philosopher_number + 1, LEFT + 1, philosopher_number + 1);
- showStatus();
- // sem_post(&S[philosopher_number]) has no effect
- // during take_fork
- // used to wake up hungry philosophers
- // during put_fork
- sem_post(&S[philosopher_number]);
- }
- }
- // take up chopsticks
- void take_fork(int philosopher_number) {
- sem_wait(&mutex);
- // state that hungry
- state[philosopher_number] = HUNGRY;
- showStatus();
- // eat if neighbours are not eating
- test(philosopher_number);
- sem_post(&mutex);
- // if unable to eat wait to be signalled
- sem_wait(&S[philosopher_number]);
- sleep(1);
- }
- // put down chopsticks
- void put_fork(int philosopher_number) {
- sem_wait(&mutex);
- // state that thinking
- state[philosopher_number] = THINKING;
- printf("\nPhilosopher %d putting fork %d and %d down\n",
- philosopher_number + 1, LEFT + 1, philosopher_number + 1);
- showStatus();
- test(LEFT);
- test(RIGHT);
- sem_post(&mutex);
- }
- void *philosopher(void *num) {
- for (int j = 0; j < 3; j++) {
- int *i = (int *) num;
- sleep(1);
- take_fork(*i);
- sleep(0);
- put_fork(*i);
- printf("\n\n");
- }
- return num;
- }
- int main() {
- std::ios_base::sync_with_stdio(false);
- std::cin.tie(nullptr);
- pthread_t thread_id[N];
- struct timespec stop{}, start{};
- clock_gettime(CLOCK_REALTIME, &start);
- std::cout << start.tv_sec << " " << start.tv_nsec << '\n';
- // initialize the semaphores
- sem_init(&mutex, 0, 1);
- for (auto & i : S)
- sem_init(&i, 0, 0);
- for (int i = 0; i < N; i++) {
- // create philosopher processes
- pthread_create(&thread_id[i], nullptr,
- philosopher, &phil[i]);
- clock_gettime(CLOCK_REALTIME, &stop);
- printf("\nAt %lu micro-seconds Philosopher %d is created and he starts thinking\n", ((stop.tv_nsec - start.tv_nsec) / 1000), i + 1);
- flag[i] = 1;
- }
- for (unsigned long i : thread_id) pthread_join(i, nullptr);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement