Uploaded by Amr Khaled

OS2 Project ZZZ (1)

advertisement
Operating System
Dining-Philosophers Problem:
Write a C++ program to implement Dining-Philosophers problem.
Project description
A group of philosophers seated about a round table eating spaghetti. There
are the same total number of forks as there are philosophers and one fork is
placed between every two philosophers that puts a single fork to the left and
right of each philosopher. The philosophers run the traditional think eat loop.
After he sits quietly thinking for a while, a philosopher gets hungry. To eat, a
philosopher grabs the fork to the left, grabs the fork to the right, eats for a
time using both forks, and then replaces the forks and goes back to thinking.
There is a possible deadlock condition if the philosophers are allowed to grab
forks freely. The deadlock occurs if no one is eating, and then all the
philosophers grab the fork to their left, and then look over and wait for the
right fork.
Code :
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;
const int NUM_PHILOSOPHERS = 5;
// Define a struct to represent a philosopher
struct Philosopher {
int id;
mutex& left_fork;
mutex& right_fork;
Philosopher(int id, mutex& left_fork,
left_fork(left_fork), right_fork(right_fork) {}
mutex&
right_fork)
:
void operator()() {
while (true) {
// Think for some time
cout << "Philosopher " << id << " is thinking..." << endl;
this_thread::sleep_for(chrono::milliseconds(1000));
// Pick up the left and right forks
left_fork.lock();
cout << "Philosopher " << id << " picked up the left fork." << endl;
right_fork.lock();
cout << "Philosopher " << id << " picked up the right fork." << endl;
// Eat for some time
cout << "Philosopher " << id << " is eating spaghetti..." << endl;
this_thread::sleep_for(chrono::milliseconds(2000));
// Release the forks
right_fork.unlock();
cout << "Continuation of the previous code:
Philosopher " << id << " put down the right fork." << endl;
id(id),
left_fork.unlock();
cout << "Philosopher " << id << " put down the left fork." << endl;
}
}
};
int main() {
// Create a mutex for each fork
mutex forks[NUM_PHILOSOPHERS];
// Create an array of philosophers
Philosopher philosophers[NUM_PHILOSOPHERS] = {
Philosopher(0, forks[0], forks[1]),
Philosopher(1, forks[1], forks[2]),
Philosopher(2, forks[2], forks[3]),
Philosopher(3, forks[3], forks[4]),
Philosopher(4, forks[4], forks[0])
};
// Create a thread for each philosopher
thread threads[NUM_PHILOSOPHERS];
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
threads[i] = thread(philosophers[i]);
}
// Wait for the threads to finish (should never happen in this case)
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
threads[i].join();
}
return 0;
}
Download