Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <chrono>
- #include <vector>
- #include "semaphore.cpp"
- std::vector<Semaphore> forkes(5);
- std::vector<int> currentPhilosopher(5, -1);
- std::mutex global_mutex;
- enum PrintType {
- START_THINK, END_THINK, START_EAT, END_EAT
- };
- void print(PrintType type, int philosopher_id) {
- std::lock_guard<decltype(global_mutex)> lock(global_mutex);
- switch (type) {
- case START_THINK:
- printf("[%d] started thinking", philosopher_id);
- case END_THINK:
- printf("[%d] ended thinking", philosopher_id);
- case START_EAT:
- printf("[%d] started eating", philosopher_id);
- case END_EAT:
- printf("[%d] ended eating", philosopher_id);
- }
- printf(", current forkes busyness is [%lu, %lu, %lu, %lu, %lu], current fork distribution is [%d, %d, %d, %d, %d]\n",
- forkes[0].getCount(),
- forkes[1].getCount(),
- forkes[2].getCount(),
- forkes[3].getCount(),
- forkes[4].getCount(),
- currentPhilosopher[0],
- currentPhilosopher[1],
- currentPhilosopher[2],
- currentPhilosopher[3],
- currentPhilosopher[4]);
- }
- void eat(int philosopher_id) {
- using namespace std::literals;
- print(START_THINK, philosopher_id);
- forkes[philosopher_id].acquire();
- currentPhilosopher[philosopher_id] = philosopher_id;
- forkes[(philosopher_id + 1) % 5].acquire();
- currentPhilosopher[(philosopher_id + 1) % 5] = philosopher_id;
- print(END_THINK, philosopher_id);
- print(START_EAT, philosopher_id);
- std::this_thread::sleep_for(1s);
- print(END_EAT, philosopher_id);
- forkes[philosopher_id].release();
- currentPhilosopher[philosopher_id] = -1;
- forkes[(philosopher_id + 1) % 5].release();
- currentPhilosopher[(philosopher_id + 1) % 5] = -1;
- eat(philosopher_id);
- }
- int main() {
- for (int i = 0; i < 5; ++i) {
- forkes[i].release();
- }
- std::vector<std::thread> philosophers;
- for (int i = 0; i < 5; ++i) {
- std::thread philosopher = std::thread(eat, i);
- philosophers.push_back(std::move(philosopher));
- }
- for (int i = 0; i < philosophers.size(); ++i) {
- philosophers[i].join();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement