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();
A deadlock happens when two threads wait for each other to finish, freezing your program. You avoid this by making sure every thread grabs resources in the same order or by using tools that automatically release resources when you are done. Think of it like a group of people waiting to use a single microphone; if everyone agrees on who speaks next and hands it back immediately, no one gets stuck waiting forever.