@@ -43,26 +43,9 @@ impl Philosopher {
43
43
async fn eat ( & self ) {
44
44
// Keep trying until we have both forks
45
45
// ANCHOR_END: Philosopher-eat
46
- let ( _left_fork, _right_fork) = loop {
47
- // Pick up forks...
48
- let left_fork = self . left_fork . try_lock ( ) ;
49
- let right_fork = self . right_fork . try_lock ( ) ;
50
- let Ok ( left_fork) = left_fork else {
51
- // If we didn't get the left fork, drop the right fork if we
52
- // have it and let other tasks make progress.
53
- drop ( right_fork) ;
54
- time:: sleep ( time:: Duration :: from_millis ( 1 ) ) . await ;
55
- continue ;
56
- } ;
57
- let Ok ( right_fork) = right_fork else {
58
- // If we didn't get the right fork, drop the left fork and let
59
- // other tasks make progress.
60
- drop ( left_fork) ;
61
- time:: sleep ( time:: Duration :: from_millis ( 1 ) ) . await ;
62
- continue ;
63
- } ;
64
- break ( left_fork, right_fork) ;
65
- } ;
46
+ // Pick up forks...
47
+ let _left_fork = self . left_fork . lock ( ) . await ;
48
+ let _right_fork = self . right_fork . lock ( ) . await ;
66
49
67
50
// ANCHOR: Philosopher-eat-body
68
51
println ! ( "{} is eating..." , & self . name) ;
@@ -89,8 +72,11 @@ async fn main() {
89
72
let mut philosophers = vec ! [ ] ;
90
73
let ( tx, rx) = mpsc:: channel ( 10 ) ;
91
74
for ( i, name) in PHILOSOPHERS . iter ( ) . enumerate ( ) {
92
- let left_fork = Arc :: clone ( & forks[ i] ) ;
93
- let right_fork = Arc :: clone ( & forks[ ( i + 1 ) % PHILOSOPHERS . len ( ) ] ) ;
75
+ let mut left_fork = Arc :: clone ( & forks[ i] ) ;
76
+ let mut right_fork = Arc :: clone ( & forks[ ( i + 1 ) % PHILOSOPHERS . len ( ) ] ) ;
77
+ if i == PHILOSOPHERS . len ( ) - 1 {
78
+ std:: mem:: swap ( & mut left_fork, & mut right_fork) ;
79
+ }
94
80
philosophers. push ( Philosopher {
95
81
name : name. to_string ( ) ,
96
82
left_fork,
0 commit comments