Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. use std::thread;
  2. use std::time::Duration;
  3. use std::sync::{Mutex, Arc};
  4.  
  5. struct Philosopher {
  6. name: String,
  7. left: usize,
  8. right: usize,
  9. }
  10.  
  11. impl Philosopher {
  12. fn new(name: &str, left: usize, right: usize) -> Philosopher {
  13. Philosopher {
  14. name: name.to_string(),
  15. left: left,
  16. right: right,
  17. }
  18. }
  19.  
  20. fn eat(&self, table: &Table) {
  21. let _left = table.forks[self.left].lock().unwrap();
  22. thread::sleep(Duration::from_millis(150));
  23. let _right = table.forks[self.right].lock().unwrap();
  24.  
  25. println!("{} is eating.", self.name);
  26.  
  27. thread::sleep(Duration::from_millis(1000));
  28.  
  29. println!("{} is done eating.", self.name);
  30. }
  31. }
  32.  
  33. struct Table {
  34. forks: Vec<Mutex<()>>,
  35. }
  36.  
  37. fn main() {
  38. let table = Arc::new(Table { forks: vec![
  39. Mutex::new(()),
  40. Mutex::new(()),
  41. Mutex::new(()),
  42. Mutex::new(()),
  43. Mutex::new(()),
  44. ]});
  45.  
  46. let philosophers = vec![
  47. Philosopher::new("Judith Butler", 0, 1),
  48. Philosopher::new("Gilles Deleuze", 1, 2),
  49. Philosopher::new("Karl Marx", 2, 3),
  50. Philosopher::new("Emma Goldman", 3, 4),
  51. Philosopher::new("Michel Foucault", 0, 4),
  52. ];
  53.  
  54. let handles: Vec<_> = philosophers.into_iter().map(|p| {
  55. let table = table.clone();
  56.  
  57. thread::spawn(move || {
  58. p.eat(&table);
  59. })
  60. }).collect();
  61.  
  62. for h in handles {
  63. h.join().unwrap();
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement