Created
May 15, 2022 09:59
-
-
Save moofkit/789085628da2a67e811082567708cfc3 to your computer and use it in GitHub Desktop.
Rust mutex deadlock example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::sync::{Arc, Mutex}; | |
use std::thread; | |
use std::time::Duration; | |
fn main() { | |
let counter = Arc::new(Mutex::new(0)); | |
let counter2 = Arc::new(Mutex::new(0)); | |
let mut handles = vec![]; | |
for _ in 0..10 { | |
let counter = Arc::clone(&counter); | |
let counter2 = Arc::clone(&counter2); | |
let handle = thread::spawn(move || { | |
let mut num = counter.lock().unwrap(); | |
let mut num2 = counter2.lock().unwrap(); | |
thread::sleep(Duration::from_millis(10)); | |
*num += 1; | |
*num2 += 1; | |
}); | |
handles.push(handle); | |
} | |
for _ in 0..10 { | |
let counter2 = Arc::clone(&counter2); | |
let counter = Arc::clone(&counter); | |
let handle = thread::spawn(move || { | |
let mut num2 = counter2.lock().unwrap(); | |
let mut num = counter.lock().unwrap(); | |
*num2 += 1; | |
*num += 1; | |
}); | |
handles.push(handle); | |
} | |
for handle in handles { | |
handle.join().unwrap(); | |
} | |
println!("Result: {}", *counter.lock().unwrap()); | |
println!("Result2: {}", *counter2.lock().unwrap()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment