I tried implementing the dining philosophers problem from what I understood in wikipedia, the solution may not be entirely right, you can suggest any changes that is necessary. Also I encountered a weird runtime error which read
Expression:vector subscript out of range
What I don't understand is, I am performing the modulus operation for index to wrap, what am I missing ?
Thanks in advance.
#include "stdafx.h"
#include "iostream"
#include "vector"
#include "algorithm"
#include "mutex"
#include "chrono"
using namespace std;
class Dining {
std::recursive_mutex arbit;
std::vector<int> chopsticks;
int count;
public:
Dining()
{
vector<int> v = { 1,2,3,4,5 };
chopsticks = v;
int count = 0;
}
private :
int acquire()
{
arbit.lock();
if (count%chopsticks.size() > 4)
cout << count%chopsticks.size();
int x = chopsticks[count%chopsticks.size()];
chopsticks[count%chopsticks.size()] = 0;
count++;
arbit.unlock();
return x;
}
void release(int i)
{
arbit.lock();
chopsticks[i - 1] = i;
arbit.unlock();
}
public:
void eatThink() {
int left, right;
left = acquire();
right = acquire();
arbit.lock();
if (left && right)
{
cout << "Thread " << std::this_thread::get_id() << "Eating" << endl;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
cout << "Thread " << std::this_thread::get_id() << "Releasing" << endl;
}
arbit.unlock();
release(left);
release(right);
}
};
int main()
{
Dining* philosophers = new Dining();
int size = 10;
std::vector<std::thread> threads(size);
for (int i = 0; i < size; i++) {
threads[i] = std::thread(&Dining::eatThink, philosophers);
}
for (int i = 0; i < threads.size(); i++) {
threads[i].join();
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire