Working example for thread- and non-thread-safe applications
This commit is contained in:
parent
11597fa330
commit
8ed8e6e50d
26
src/bin/arcmutex.rs
Normal file
26
src/bin/arcmutex.rs
Normal 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
30
src/bin/rcrefcell.rs
Normal 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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user