Working example for thread- and non-thread-safe applications

This commit is contained in:
Fabian Schmidt 2024-02-20 16:43:58 +01:00
parent 11597fa330
commit 8ed8e6e50d
2 changed files with 56 additions and 0 deletions

26
src/bin/arcmutex.rs Normal file
View File

@ -0,0 +1,26 @@
use std::sync::{Arc, Mutex};
fn c<F: FnOnce() + 'static>(f: F) {
f();
}
fn main() {
let v = Arc::new(Mutex::new(vec![1, 2, 3]));
c({
let v = v.clone();
move || {
println!("inner 1: {:?}", v);
v.lock().unwrap().push(4);
}
});
c({
let v = v.clone();
move || {
println!("inner 2: {:?}", v);
v.lock().unwrap().push(5);
}
});
println!("outer: {:?}", v);
}

30
src/bin/rcrefcell.rs Normal file
View File

@ -0,0 +1,30 @@
use std::{cell::RefCell, rc::Rc};
fn c<F: FnOnce() + 'static>(f: F) {
f();
}
fn main() {
let v = Rc::new(RefCell::new(vec![1, 2, 3]));
c({
let v = v.clone();
move || {
println!("inner 1: {:?}", v);
v.replace_with(|old| {
old.push(4);
old.to_vec()
});
}
});
c({
let v = v.clone();
move || {
println!("inner 2: {:?}", v);
// This seems more readable than the example from https://www.youtube.com/watch?v=FTsaDmf0f_0 shown above
v.borrow_mut().push(5);
}
});
println!("outer: {:?}", v);
}