@@ -512,6 +512,7 @@ impl Philosopher {
512
512
513
513
fn eat (& self , table : & Table ) {
514
514
let _left = table . forks[self . left]. lock (). unwrap ();
515
+ thread :: sleep_ms (150 );
515
516
let _right = table . forks[self . right]. lock (). unwrap ();
516
517
517
518
println! (" {} is eating." , self . name);
@@ -597,6 +598,7 @@ We now need to construct those `left` and `right` values, so we add them to
597
598
``` rust,ignore
598
599
fn eat(&self, table: &Table) {
599
600
let _left = table.forks[self.left].lock().unwrap();
601
+ thread::sleep_ms(150);
600
602
let _right = table.forks[self.right].lock().unwrap();
601
603
602
604
println!("{} is eating.", self.name);
@@ -607,11 +609,14 @@ fn eat(&self, table: &Table) {
607
609
}
608
610
```
609
611
610
- We have two new lines. We’ve also added an argument, ` table ` . We access the
612
+ We have three new lines. We’ve added an argument, ` table ` . We access the
611
613
` Table ` ’s list of forks, and then use ` self.left ` and ` self.right ` to access
612
614
the fork at that particular index. That gives us access to the ` Mutex ` at that
613
615
index, and we call ` lock() ` on it. If the mutex is currently being accessed by
614
- someone else, we’ll block until it becomes available.
616
+ someone else, we’ll block until it becomes available. We have also a call to
617
+ ` thread::sleep_ms ` between the moment first fork is picked and the moment the
618
+ second forked is picked, as the process of picking up the fork is not
619
+ immediate.
615
620
616
621
The call to ` lock() ` might fail, and if it does, we want to crash. In this
617
622
case, the error that could happen is that the mutex is [ ‘poisoned’] [ poison ] ,
@@ -660,7 +665,9 @@ We need to pass in our `left` and `right` values to the constructors for our
660
665
you look at the pattern, it’s all consistent until the very end. Monsieur
661
666
Foucault should have ` 4, 0 ` as arguments, but instead, has ` 0, 4 ` . This is what
662
667
prevents deadlock, actually: one of our philosophers is left handed! This is
663
- one way to solve the problem, and in my opinion, it’s the simplest.
668
+ one way to solve the problem, and in my opinion, it’s the simplest. If you
669
+ change the order of the parameters, you will be able to observe the deadlock
670
+ taking place.
664
671
665
672
``` rust,ignore
666
673
let handles: Vec<_> = philosophers.into_iter().map(|p| {
0 commit comments