Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::sync::Mutex;
- struct S {
- m: Mutex<i32>,
- x: u32,
- }
- impl S {
- fn new() -> Self {
- Self {
- m: Mutex::new(0),
- x: 0
- }
- }
- fn immutable_borrow(&self) -> u32 {
- self.x
- }
- fn mutable_borrow(&mut self) {
- self.x += 1;
- }
- fn critical_section(&self) {
- // Enter critical section
- let mut guard = self.m.lock().unwrap();
- *guard += 1;
- // Leave critical section
- }
- }
- fn main() {
- let s = S::new();
- // Enter critical section, borrow `s` immutably
- let _guard = s.m.lock();
- // It's ok to borrow `s` immutably again.
- let _ = s.immutable_borrow();
- // `s` cannot be borrowed mutably when it's already borrowed immutably
- // s.mutable_borrow();
- // belong
- // +-------------------+
- // | |
- // v |
- // current thread mutex m
- // | ^
- // | |
- // +------------------+
- // require
- //
- // Lead to a deadlock when requiring a locked mutex.
- // s.critical_section();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement