|
| 1 | +% Dining Philosophers |
| 2 | + |
| 3 | +For our second project, let’s look at a classic concurrency problem. It’s |
| 4 | +called ‘the dining philosophers’. It was originally conceived by Dijkstra in |
| 5 | +1965, but we’ll use the version from [this paper][paper] by Tony Hoare in 1985. |
| 6 | + |
| 7 | +[paper]: http://www.usingcsp.com/cspbook.pdf |
| 8 | + |
| 9 | +> In ancient times, a wealthy philanthropist endowed a College to accommodate |
| 10 | +> five eminent philosophers. Each philosopher had a room in which he could |
| 11 | +> engage in his professional activity of thinking; there was also a common |
| 12 | +> dining room, furnished with a circular table, surrounded by five chairs, each |
| 13 | +> labelled by the name of the philosopher who was to sit in it. They sat |
| 14 | +> anticlockwise around the table. To the left of each philosopher there was |
| 15 | +> laid a golden fork, and in the centre stood a large bowl of spaghetti, which |
| 16 | +> was constantly replenished. A philosopher was expected to spend most of his |
| 17 | +> time thinking; but when he felt hungry, he went to the dining room, sat down |
| 18 | +> in his own chair, picked up his own fork on his left, and plunged it into the |
| 19 | +> spaghetti. But such is the tangled nature of spaghetti that a second fork is |
| 20 | +> required to carry it to the mouth. The philosopher therefore had also to pick |
| 21 | +> up the fork on his right. When we was finished he would put down both his |
| 22 | +> forks, get up from his chair, and continue thinking. Of course, a fork can be |
| 23 | +> used by only one philosopher at a time. If the other philosopher wants it, he |
| 24 | +> just has to wait until the fork is available again. |
| 25 | +
|
| 26 | + |
| 27 | +```rust |
| 28 | +struct Philosopher { |
| 29 | + name: String, |
| 30 | +} |
| 31 | + |
| 32 | +impl Philosopher { |
| 33 | + fn new(name: &str) -> Philosopher { |
| 34 | + Philosopher { |
| 35 | + name: name.to_string(), |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +fn main() { |
| 41 | + let p1 = Philosopher::new(“Baruch Spinoza”); |
| 42 | + let p2 = Philosopher::new(“Gilles Deleuze”); |
| 43 | + let p3 = Philosopher::new(“Karl Marx”); |
| 44 | + let p4 = Philosopher::new(“Friedrich Nietzsche”); |
| 45 | + let p5 = Philosopher::new(“Michel Foucault”); |
| 46 | +} |
| 47 | +``` |
0 commit comments