Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Dining Philosopher's problem: Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers. Each

Dining Philosopher's problem:

Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.

Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks.

Begin by creating 5 philosophers, each identified by a number from 0 to 4. Each philosopher runs as a seperate thread. Philosophers alternate between thinking and eating. In order to simulate these activities each thread will sleep between 1 to 3 seconds.

In order to eat the philosopher invokes the function pickup_forks (int philosopher_number)

When the philosopher is done eating they invoke the function return_forks(int philosopher_number);

Pthread Condition Variable:

The following condition/mutex variables/functions must be included in your code:

pthread_mutex_t mutex;

pthread_cond_t cond_var;

pthread_mutex_init(&mutex, NULL);

pthread_cond_init(&cond_var, NULL);

pthread_cond_wait(&cond_var, &mutex);

pthread_cond_signal(&cond_var);

pthread_mutex_lock(&mutex);

pthread_mutex_unlock(&mutex);

Below is some code to help you get started:

#include  #include  #include  #include  void *dine(); int chopsticks[5]; int main(int argc, char *argv[]) { int i, rc; pthread_t philsophers[5]; srand(time(NULL)); /* Initialize chopsticks */ for (i=0; i<5; ++i) { chopsticks[i]=0; } /* Spawn threads */ for (i=0; i<5; ++i) { if( (rc=pthread_create( &philsophers[i], NULL, &dine, &i)) ) printf("Thread creation failed: %d ", rc); sleep(1); } /* Wait for thread completion */ for (i=0; i<5; ++i) pthread_join( philsophers[i], NULL); exit(0); } think(int pnum) { } eat(int pnum) { } void *dine(void *pnum_ptr) { int pnum = *(int*)pnum_ptr; printf("Created philosopher thread %d ", pnum); while (1) { think(pnum); eat(pnum); } } 

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions