I would like my program to have an output like at the bottom #include #include #include #include #define N 4 #define THINKING 2 #define HUNGRY 1 #define Eating 0 #define left_neighbor (phnum + 4) % N #define right_neighbor (phnum + 1) % N int state[N]; int phil[N] = { 0, 1, 2, 3 }; sem_t mutex; sem_t S[N]; void test(int phnum) { if (state[phnum] == HUNGRY && state[left_neighbor] != Eating && state[right_neighbor] != Eating) { // Philospher EATING state[phnum] = Eating; sleep(2); printf("PHIL %d EATING\n", phnum + 1); sem_post(&S[phnum]); } state[phnum] = HUNGRY; printf("PHIL %d HUNGRY\n", phnum + 1); // eat if neighbor are not eating_turn test(phnum); sem_post(&mutex); sem_wait(&S[phnum]); sleep(1); } { printf("PHIL %d is THINKING\n", phnum + 1); test(left_neighbor); test(right_neighbor); sem_post(&mutex); } void* philosphr(void* num) { while (1) { int* i = num; sleep(1); sleep(0); } } int main() { int i; pthread_t thread_id[N]; // initiate the semaphores sem_init(&mutex, 0, 1); for (i = 0; i < N; i++) sem_init(&S[i], 0, 0); for (i = 0; i < N; i++) { pthread_create(&thread_id[i], NULL, philosphr, &phil[i]); printf("PHIL %d THINKING\n", i + 1); } for (i = 0; i < N; i++) pthread_join(thread_id[i], NULL); }
I would like my program to have an output like at the bottom
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#define N 4
#define THINKING 2
#define HUNGRY 1
#define Eating 0
#define left_neighbor (phnum + 4) % N
#define right_neighbor (phnum + 1) % N
int state[N];
int phil[N] = { 0, 1, 2, 3 };
sem_t mutex;
sem_t S[N];
void test(int phnum)
{
if (state[phnum] == HUNGRY
&& state[left_neighbor] != Eating
&& state[right_neighbor] != Eating)
{
// Philospher EATING
state[phnum] = Eating;
sleep(2);
printf("PHIL %d EATING\n", phnum + 1);
sem_post(&S[phnum]);
}
state[phnum] = HUNGRY;
printf("PHIL %d HUNGRY\n", phnum + 1);
// eat if neighbor are not eating_turn
test(phnum);
sem_post(&mutex);
sem_wait(&S[phnum]);
sleep(1);
}
{
printf("PHIL %d is THINKING\n", phnum + 1);
test(left_neighbor);
test(right_neighbor);
sem_post(&mutex);
}
void* philosphr(void* num)
{
while (1)
{
int* i = num;
sleep(1);
sleep(0);
}
}
int main()
{
int i;
pthread_t thread_id[N];
// initiate the semaphores
sem_init(&mutex, 0, 1);
for (i = 0; i < N; i++)
sem_init(&S[i], 0, 0);
for (i = 0; i < N; i++) {
pthread_create(&thread_id[i], NULL,
philosphr, &phil[i]);
printf("PHIL %d THINKING\n", i + 1);
}
for (i = 0; i < N; i++)
pthread_join(thread_id[i], NULL);
}
Step by step
Solved in 2 steps