# 1226.the-dining-philosophers

## Statement

5 个沉默寡言的哲学家围坐在圆桌前，每人面前一盘意面。叉子放在哲学家之间的桌面上。（5 个哲学家，5 根叉子）

• `philosopher` 哲学家的编号。
• `pickLeftFork` 和 `pickRightFork` 表示拿起左边或右边的叉子。
• `eat` 表示吃面。
• `putLeftFork` 和 `putRightFork` 表示放下左边或右边的叉子。
• 由于哲学家不是在吃面就是在想着啥时候吃面，所以思考这个方法没有对应的回调。

``````输入：n = 1

n 表示每个哲学家需要进餐的次数。

output[i] = [a, b, c] (3个整数)
- a 哲学家编号。
- b 指定叉子：{1 : 左边, 2 : 右边}.
- c 指定行为：{1 : 拿起, 2 : 放下, 3 : 吃面}。

``````

• `1 <= n <= 60`

Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.

Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks.

Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed.

Design a discipline of behaviour (a concurrent algorithm) such that no philosopher will starve; i.e., each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think.

The problem statement and the image above are taken from wikipedia.org

The philosophers' ids are numbered from 0 to 4 in a clockwise order. Implement the function `void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork)` where:

• `philosopher` is the id of the philosopher who wants to eat.
• `pickLeftFork` and `pickRightFork` are functions you can call to pick the corresponding forks of that philosopher.
• `eat` is a function you can call to let the philosopher eat once he has picked both forks.
• `putLeftFork` and `putRightFork` are functions you can call to put down the corresponding forks of that philosopher.
• The philosophers are assumed to be thinking as long as they are not asking to eat (the function is not being called with their number).

Five threads, each representing a philosopher, will simultaneously use one object of your class to simulate the process. The function may be called for the same philosopher more than once, even before the last call ends.

Example 1:

``````Input: n = 1
Output: [[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]]
Explanation:
n is the number of times each philosopher will call the function.
The output array describes the calls you made to the functions controlling the forks and the eat function, its format is:
output[i] = [a, b, c] (three integers)
- a is the id of a philosopher.
- b specifies the fork: {1 : left, 2 : right}.
- c specifies the operation: {1 : pick, 2 : put, 3 : eat}.``````

Constraints:

• `1 <= n <= 60`

## Solution

``````#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define endl "\n"
#define fi first
#define se second
#define all(x) begin(x), end(x)
#define rall rbegin(a), rend(a)
#define bitcnt(x) (__builtin_popcountll(x))
#define complete_unique(a) a.erase(unique(begin(a), end(a)), end(a))
#define mst(x, a) memset(x, a, sizeof(x))
#define MP make_pair

using ll = long long;
using ull = unsigned long long;
using db = double;
using ld = long double;
using VLL = std::vector<ll>;
using VI = std::vector<int>;
using PII = std::pair<int, int>;
using PLL = std::pair<ll, ll>;

using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

template <typename T, typename S>
inline bool chmax(T &a, const S &b) {
return a < b ? a = b, 1 : 0;
}

template <typename T, typename S>
inline bool chmin(T &a, const S &b) {
return a > b ? a = b, 1 : 0;
}

#ifdef LOCAL
#include <debug.hpp>
#else
#define dbg(...)
#endif

enum class State {
UNKNOWN,
HOLD_ONE,
HOLD_TWO,
AFTER_EAT,
PUT_ONE,
};

struct Node {
int left_num{0};
int right_num{0};
bool hold_left{false};
bool hold_right{false};
};

class DiningPhilosophers {
public:
DiningPhilosophers() {
node_ = vector<Node>(n_);
fork_state_ = vector<int>(n_, 0);

for (int i = 0; i < n_; i++) {
auto &node = node_[i];
node.left_num = i;
node.right_num = (i + 1) % n_;
}
}

void wantsToEat(int philosopher, function<void()> pickLeftFork, function<void()> pickRightFork,
function<void()> eat, function<void()> putLeftFork, function<void()> putRightFork) {
auto &node = node_[philosopher];

std::unique_lock<std::mutex> lock(mutex_);

if (fork_state_[node.left_num] == 0) {
fork_state_[node.left_num] = 1;
node.hold_left = true;
node.state = State::HOLD_ONE;
pickLeftFork();
} else if (fork_state_[node.right_num] == 0) {
fork_state_[node.right_num] = 1;
node.hold_right = true;
node.state = State::HOLD_ONE;
pickRightFork();
}
} else if (node.state == State::HOLD_ONE) {
if (node.hold_left) {
if (fork_state_[node.right_num] == 0) {
fork_state_[node.right_num] = 1;
node.hold_right = true;
node.state = State::HOLD_TWO;
pickRightFork();
} else {
fork_state_[node.left_num] = 0;
node.hold_left = false;
putLeftFork();
}
} else {
if (fork_state_[node.left_num] == 0) {
fork_state_[node.left_num] = 1;
node.hold_left = true;
node.state = State::HOLD_TWO;
pickLeftFork();
} else {
fork_state_[node.right_num] = 0;
node.hold_right = false;
pickRightFork();
}
}
} else if (node.state == State::HOLD_TWO) {
node.state = State::AFTER_EAT;
eat();
} else if (node.state == State::AFTER_EAT) {
fork_state_[node.right_num] = 0;
node.hold_right = false;
node.state = State::PUT_ONE;
putRightFork();
} else if (node.state == State::PUT_ONE) {
fork_state_[node.left_num] = 0;
node.hold_left = false;
putLeftFork();
}
}

private:
vector<Node> node_{};
std::vector<int> fork_state_{};
std::mutex mutex_{};

inline const static int n_ = 5;
};

#ifdef LOCAL

int main() {
return 0;
}

#endif
``````

## Solution1

``````#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define endl "\n"
#define fi first
#define se second
#define all(x) begin(x), end(x)
#define rall rbegin(a), rend(a)
#define bitcnt(x) (__builtin_popcountll(x))
#define complete_unique(a) a.erase(unique(begin(a), end(a)), end(a))
#define mst(x, a) memset(x, a, sizeof(x))
#define MP make_pair

using ll = long long;
using ull = unsigned long long;
using db = double;
using ld = long double;
using VLL = std::vector<ll>;
using VI = std::vector<int>;
using PII = std::pair<int, int>;
using PLL = std::pair<ll, ll>;

using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

template <typename T, typename S>
inline bool chmax(T &a, const S &b) {
return a < b ? a = b, 1 : 0;
}

template <typename T, typename S>
inline bool chmin(T &a, const S &b) {
return a > b ? a = b, 1 : 0;
}

#ifdef LOCAL
#include <debug.hpp>
#else
#define dbg(...)
#endif

// [[0,1,1],[0,2,1],[0,0,3],[0,1,2],[2,1,1],[2,2,1],[2,0,3],[2,1,2],[2,2,2],[3,1,1],[3,2,1],[3,0,3],[3,1,2],[3,2,2],[4,1,1],[4,2,1],[4,0,3],[4,1,2],[4,2,2],[0,2,2],[1,1,1],[1,2,1],[1,0,3],[1,1,2],[1,2,2]]
// [[0,1,1],[0,2,1],[0,0,3],[0,1,2],[0,2,2],[2,1,1],[2,2,1],[1,1,1],[2,0,3],[2,1,2],[1,2,1],[4,1,1],[4,2,1],[2,2,2],[3,1,1],[1,0,3],[1,1,2],[1,2,2],[4,0,3],[4,1,2],[4,2,2],[3,2,1],[3,0,3],[3,1,2],[3,2,2]]
// [[0,1,1],[0,2,1],[0,0,3],[0,1,2],[0,2,2],[1,1,1],[1,2,1],[1,0,3],[1,1,2],[3,1,1],[3,2,1],[3,0,3],[3,1,2],[3,2,2],[4,1,1],[4,2,1],[4,0,3],[4,1,2],[4,2,2],[1,2,2],[2,1,1],[2,2,1],[2,0,3],[2,1,2],[2,2,2]]

enum class State {
HOLD_ONE,
HOLD_TWO,
AFTER_EAT,
};

class DiningPhilosophers {
public:
DiningPhilosophers() {
fork_state_ = vector<int>(n_, 0);
mutex_list_ = vector<std::mutex>(n_);
cond_list_ = vector<std::condition_variable>(n_);
}

void wantsToEat(int philosopher, function<void()> pickLeftFork, function<void()> pickRightFork,
function<void()> eat, function<void()> putLeftFork, function<void()> putRightFork) {
int left_num = philosopher;
int right_num = (philosopher + 1) % n_;

if (left_num > right_num) {
swap(left_num, right_num);
}

while (true) {
std::invoke([&]() {
std::unique_lock<std::mutex> lock(mutex_list_[left_num]);

cond_list_[left_num].wait_for(lock, 100ms, [&]() {
return fork_state_[left_num] == 0;
});

if (fork_state_[left_num] == 1) {
return;
}

pickLeftFork();

fork_state_[left_num] = 1;
s = State::HOLD_ONE;
});
} else if (s == State::HOLD_ONE) {
std::invoke([&]() {
std::unique_lock<std::mutex> lock(mutex_list_[right_num]);

cond_list_[right_num].wait_for(lock, 100ms, [&]() {
return fork_state_[right_num] == 0;
});

if (fork_state_[right_num] == 1) {
return;
}

fork_state_[right_num] = 1;
s = State::HOLD_TWO;
pickRightFork();

std::unique_lock<std::mutex> lock_left(mutex_list_[left_num]);

eat();

putLeftFork();
fork_state_[left_num] = 0;
cond_list_[left_num].notify_all();

putRightFork();
fork_state_[right_num] = 0;
cond_list_[right_num].notify_all();

s = State::AFTER_EAT;
});

std::invoke([&]() {
if (s != State::HOLD_ONE) {
return;
}

std::unique_lock<std::mutex> lock(mutex_list_[left_num]);

fork_state_[left_num] = 0;
putLeftFork();
cond_list_[left_num].notify_all();
});

} else if (s == State::HOLD_TWO) {
std::unique_lock<std::mutex> lock(mutex_list_[left_num]);
std::unique_lock<std::mutex> lock_right(mutex_list_[right_num]);

eat();

putLeftFork();
fork_state_[left_num] = 0;
cond_list_[left_num].notify_all();

putRightFork();
fork_state_[right_num] = 0;
cond_list_[right_num].notify_all();

// std::invoke([&]() {
//     std::unique_lock<std::mutex> lock(mutex_list_[left_num]);

// });

// std::invoke([&]() {
//     std::unique_lock<std::mutex> lock(mutex_list_[right_num]);

// });

break;
} else if (s == State::AFTER_EAT) {
break;
}
}
}

private:
std::vector<int> fork_state_{};
std::vector<std::mutex> mutex_list_{};
std::vector<std::condition_variable> cond_list_{};

inline const static int n_ = 5;
};

#ifdef LOCAL

int main() {
return 0;
}

#endif
``````

## Solution2

``````#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define endl "\n"
#define fi first
#define se second
#define all(x) begin(x), end(x)
#define rall rbegin(a), rend(a)
#define bitcnt(x) (__builtin_popcountll(x))
#define complete_unique(a) a.erase(unique(begin(a), end(a)), end(a))
#define mst(x, a) memset(x, a, sizeof(x))
#define MP make_pair

using ll = long long;
using ull = unsigned long long;
using db = double;
using ld = long double;
using VLL = std::vector<ll>;
using VI = std::vector<int>;
using PII = std::pair<int, int>;
using PLL = std::pair<ll, ll>;

using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

template <typename T, typename S>
inline bool chmax(T &a, const S &b) {
return a < b ? a = b, 1 : 0;
}

template <typename T, typename S>
inline bool chmin(T &a, const S &b) {
return a > b ? a = b, 1 : 0;
}

#ifdef LOCAL
#include <debug.hpp>
#else
#define dbg(...)
#endif

enum class State {
HOLD_ONE,
HOLD_TWO,
};

class DiningPhilosophers {
public:
DiningPhilosophers() {
mutex_list_ = vector<std::mutex>(n_);
}

void wantsToEat(int philosopher, function<void()> pickLeftFork, function<void()> pickRightFork,
function<void()> eat, function<void()> putLeftFork, [[maybe_unused]] function<void()> putRightFork) {
int left_num = philosopher;
int right_num = (philosopher + 1) % n_;

if (left_num > right_num) {
swap(left_num, right_num);
}

std::unique_lock<std::mutex> lock_left(mutex_list_[left_num]);
std::unique_lock<std::mutex> lock_right(mutex_list_[right_num]);

pickLeftFork();
pickRightFork();
eat();
putLeftFork();
putRightFork();
}

private:
std::vector<std::mutex> mutex_list_{};

inline const static int n_ = 5;
};

#ifdef LOCAL

int main() {
return 0;
}

#endif
``````