How to avoid deadlocks

Prevent deadlocks in Rust by using Mutex to guard shared data and ensuring consistent lock ordering so threads do not wait indefinitely.

Avoid deadlocks by ensuring threads acquire locks in a consistent global order or by using Mutex<T> with lock() to guard shared data, relying on Rust's MutexGuard to release locks automatically when they go out of scope.

use std::sync::Mutex;
use std::thread;

let counter = Mutex::new(0);
let handle = thread::spawn(move || {
    let mut num = counter.lock().unwrap();
    *num += 1;
    // Lock released automatically when `num` goes out of scope
});
handle.join().unwrap();