dining-philosophers/src/main.cpp

47 lines
1.5 KiB
C++

#include <iostream>
#include <memory>
#include <list>
#include <string>
#include <thread>
#include <cstdio>
#include <random>
#include <philosopher.hpp>
class Philosopher;
void
findNumberOfPhilosophersInParams(const int argc, char **argv, int *const numberOfPhilosophers);
int
main(int argc, char **argv) {
ListOfPhilosophersPtr philosophers;
philosophers = ListOfPhilosophersPtr(new ListOfPhilosophers());
int numberOfPhilosophers = 5;
findNumberOfPhilosophersInParams(argc, argv, &numberOfPhilosophers);
printf("%d philosophers to create.\n", numberOfPhilosophers);
for (int i = 0; i < numberOfPhilosophers; i++) {
printf("Creating philosopher: %d.\n", i);
philosophers->push_back(PhilosopherPtr(new Philosopher(philosophers, i)));
}
std::vector<std::jthread> threads;
for (unsigned long int i = 0; i < philosophers->size(); i++) {
std::shared_ptr<unsigned long> numberOfPhilosopher(new unsigned long(i));
threads.push_back(std::jthread([philosophers, numberOfPhilosopher] {
(*philosophers)[*numberOfPhilosopher]->startThread();
} ));
}
}
void
findNumberOfPhilosophersInParams(const int argc, char **argv, int *const numberOfPhilosophers) {
if (argc >= 2) {
const char *numberOfPhilosophersAsString = argv[1];
try {
*numberOfPhilosophers = std::stoi(numberOfPhilosophersAsString, NULL, 10);
} catch (std::exception &ex) {
printf("Unable to read the number of philosophers, continuing\n");
}
}
}