我不确定它为什么会挂起my.rw.write();
。
如果您取消注释sleep
呼叫,它工作正常。这意味着在 spawn 线程执行并释放RwLock
. 我觉得理论上应该没问题。我哪里错了?
use std::sync::Arc;
use std::sync::RwLock;
use std::{thread, time};
struct MySt {
num1: i64,
num2: i64,
rw: RwLock<Vec<i64>>,
}
fn main() {
let my = Arc::new(MySt {
num1: 32,
num2: 64,
rw: RwLock::new(vec![1, 2, 3]),
});
let my2 = my.clone();
let t = thread::spawn(move || {
let mut rw = my2.rw.write().unwrap();
rw[0] = 5;
println!("child thread {}, {}, {}, {}", my2.num1, my2.num2, rw[0], rw[1]);
});
//thread::sleep(time::Duration::from_millis(1000));
let mut rw = my.rw.write().unwrap();
rw[1] = 6;
println!("main thread {}, {}, {}, {}", my.num1, my.num2, rw[0], rw[1]);
t.join().unwrap();
}