rcrefcell/src/bin/thread_interior_mutability.rs

51 lines
1.1 KiB
Rust

// https://www.youtube.com/watch?v=HwupNf9iCJk
use std::{
sync::{Arc, RwLock},
thread,
};
#[derive(Debug)]
struct Node {
// RwLock similar to RefCell but thread safe,
// can also use Mutex and then .lock() it instead of calling .read() or .write()
str_val: RwLock<String>,
adjacent: Vec<Arc<Node>>,
}
fn add_urgency(node: Arc<Node>) {
{
node.str_val.write().unwrap().push('!');
}
for adj in node.adjacent.iter() {
add_urgency(adj.clone());
}
}
fn main() {
let a = Arc::new(Node {
str_val: RwLock::new(String::from("aaa")),
adjacent: vec![],
});
let b = Arc::new(Node {
str_val: RwLock::new(String::from("bbb")),
adjacent: vec![a.clone()],
});
let c = Arc::new(Node {
str_val: RwLock::new(String::from("ccc")),
adjacent: vec![a.clone()],
});
dbg!(a.clone());
dbg!(b.clone());
dbg!(c.clone());
let t1_b = b.clone();
let _t1 = thread::spawn(move || add_urgency(t1_b)).join();
dbg!(c.clone());
let t2_c = c.clone();
let _t2 = thread::spawn(move || add_urgency(t2_c)).join();
dbg!(c.clone());
}