面试题答案
一键面试思路
为了避免死锁,确保两个线程以相同的顺序获取锁。可以规定一个固定的锁获取顺序,例如先获取L1
再获取L2
。
关键代码片段
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let l1 = Arc::new(Mutex::new(()));
let l2 = Arc::new(Mutex::new(()));
let l1_clone = l1.clone();
let l2_clone = l2.clone();
let handle1 = thread::spawn(move || {
let _guard1 = l1_clone.lock().unwrap();
let _guard2 = l2_clone.lock().unwrap();
// 线程A的业务逻辑
});
let handle2 = thread::spawn(move || {
let _guard1 = l1.lock().unwrap();
let _guard2 = l2.lock().unwrap();
// 线程B的业务逻辑
});
handle1.join().unwrap();
handle2.join().unwrap();
}
在上述代码中,线程A
和线程B
都先获取L1
,再获取L2
,从而避免了死锁。