目的:
有一个数据,需要获取新值,需要在其他线程中操作.
代码:
use std::{
ops::Deref,
sync::{Arc, RwLock},
};
#[derive(Debug, Clone)]
pub struct TestArc {
inner: Arc<TestArcInner>,
}
impl Deref for TestArc {
type Target = Arc<TestArcInner>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
#[derive(Debug, Clone)]
pub struct TestArcInner {
field1: Arc<RwLock<i32>>,
}
impl TestArcInner {
pub fn change(&self,new_val:i32) {
let mut w = self.field1.write().unwrap();
*w = new_val;
}
}
fn main() {
let test1 = TestArc {
inner: Arc::new(TestArcInner {
field1: Arc::new(RwLock::new(1)),
}),
};
let test2 = test1.clone();
let handle = std::thread::spawn(move||{
test2.change(2);
println!("==========\n2:{:#?}",test2);
});
handle.join().unwrap();
println!("==========\n1:{:#?}\n==========", test1);
}
输出:
[ra@ubuntu test-arc]$ cargo run
Compiling test-arc v0.1.0 (/src/rust/test-arc)
Finished dev [unoptimized + debuginfo] target(s) in 0.36s
Running `target/debug/test-arc`
==========
2:TestArc {
inner: TestArcInner {
field1: RwLock {
data: 2,
},
},
}
==========
1:TestArc {
inner: TestArcInner {
field1: RwLock {
data: 2,
},
},
}
==========
[ra@ubuntu test-arc]$