Objective: The dining philosophers is a classical problem to represent deadlocks and how to avoid them. Typically, you have multiple philosophers and they alternate between thinking about things, eating. In this version of the program we are only going to use 2 philosophers, and each one already has a chopstick. There will be 1 free chopstick to grab when they are ready to eat, and then put back down when they are done! This project is designed to teach you how to use semaphores with multiple threads!
On the 2nd page you can see a skeleton of what your code should could be set up like, but the main requirements are as follows:
For the "eat" function:
SAMPLE EXECUTION: see image.
SKELETON: **Hint you should only need these includes**
#include < stdio.h >
#include < stdlib.h >
#include < pthread.h >
#include < semaphore.h >
//declare your global variables
const char *a[2] = {"Socrates", "Plato"};
const char *topics[5] = {"boats", "the economy", "astronomy", "what to eat", "McDonald's Szechuan Sauce");
sem t semaphore;
void* eat(void* arg) {
/* allow the first philosopher to access their critical section (aka: "Socrates has grabbed the chopstick and started eating"). Have this philosopher eat for a random amount of time, but max 10 seconds*/
/*For the philosopher that gets trapped by the semaphore have a print statement such as "Socrates cannot grab the chopstick because it is in use*/ // At the end of the critical section don't forget to release the trapped philosopher!!
}
void think(int phil) {
// have the chosen philosopher think about something.
}
int main() {
//initialize your semaphore
//initialize your thread variables
while(1) {
//randomly decide which philosopher's turn it is
//randomly decide what action that philosopher will take
if(action == "think") {
// have the philosopher perform the think action
} else {
// this will be the "eat" block
if(randomPhilsopher == Plato) {
//create a thread passing Plato's name to eat function
// create a thread passing Socrates name to eat function
} else {
// create a thread passing Socrates name to eat function
//create a thread passing Plato's name to eat function
}
}
}
//should never reach here.
return 0;
}