Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. use std::sync::Mutex;
  2.  
  3. struct S {
  4. m: Mutex<i32>,
  5. x: u32,
  6. }
  7.  
  8. impl S {
  9. fn new() -> Self {
  10. Self {
  11. m: Mutex::new(0),
  12. x: 0
  13. }
  14. }
  15.  
  16. fn immutable_borrow(&self) -> u32 {
  17. self.x
  18. }
  19.  
  20. fn mutable_borrow(&mut self) {
  21. self.x += 1;
  22. }
  23.  
  24. fn critical_section(&self) {
  25. // Enter critical section
  26. let mut guard = self.m.lock().unwrap();
  27. *guard += 1;
  28. // Leave critical section
  29. }
  30. }
  31.  
  32. fn main() {
  33. let s = S::new();
  34.  
  35. // Enter critical section, borrow `s` immutably
  36. let _guard = s.m.lock();
  37.  
  38. // It's ok to borrow `s` immutably again.
  39. let _ = s.immutable_borrow();
  40.  
  41. // `s` cannot be borrowed mutably when it's already borrowed immutably
  42. // s.mutable_borrow();
  43.  
  44.  
  45. // belong
  46. // +-------------------+
  47. // | |
  48. // v |
  49. // current thread mutex m
  50. // | ^
  51. // | |
  52. // +------------------+
  53. // require
  54. //
  55. // Lead to a deadlock when requiring a locked mutex.
  56. // s.critical_section();
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement