Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <bitset>
- #include <thread>
- #include <chrono>
- #include <vector>
- #include "semaphore.cpp"
- std::vector<Semaphore> forkes(5);
- void eat(int philosopher_id) {
- using namespace std::literals;
- printf("[%d] started thinking, current forkes busyness is [%lu, %lu, %lu, %lu, %lu]\n",
- philosopher_id,
- forkes[0].getCount(),
- forkes[1].getCount(),
- forkes[2].getCount(),
- forkes[3].getCount(),
- forkes[4].getCount());
- forkes[philosopher_id].acquire();
- forkes[(philosopher_id + 1) % 5].acquire();
- printf("[%d] ended thinking, current forkes busyness is [%lu, %lu, %lu, %lu, %lu]\n",
- philosopher_id,
- forkes[0].getCount(),
- forkes[1].getCount(),
- forkes[2].getCount(),
- forkes[3].getCount(),
- forkes[4].getCount());
- printf("[%d] started eating, current forkes busyness is [%lu, %lu, %lu, %lu, %lu]\n",
- philosopher_id,
- forkes[0].getCount(),
- forkes[1].getCount(),
- forkes[2].getCount(),
- forkes[3].getCount(),
- forkes[4].getCount());
- std::this_thread::sleep_for(1s);
- printf("[%d] ended eating, current forkes busyness is [%lu, %lu, %lu, %lu, %lu]\n",
- philosopher_id,
- forkes[0].getCount(),
- forkes[1].getCount(),
- forkes[2].getCount(),
- forkes[3].getCount(),
- forkes[4].getCount());
- forkes[philosopher_id].release();
- forkes[(philosopher_id + 1) % 5].release();
- 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