Lecture Note 6
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
Reference counter approach
- if the count of the references == 0, we can free the object
- suppose creating a new reference counter from the new one
- suppose destroying a new reference counter a
Reference counter shouldn't be sended to another thread
- thread T1 and T2 has access to
rc
- concurrent access the same object fof
rc
leads to shared mutable state
Rust concurrency libraries
- thread
- scoped thread
pub fn scope<'env, F, T>(f: F) -> T
where F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> T,
'scope
: lifetime of scope'env
: lifetime of the objects borrowed (thus used) by scoped threads;'env: 'scope
should be guaranteed
thread::scope(|s| {
s.spawn(|| {
println!("hello from the first scoped thread");
// We can borrow `a` here.
dbg!(&a);
});
s.spawn(|| {
println!("hello from the second scoped thread");
// We can even mutably borrow `x` here,
// because no other threads are using it.
x += a[0] + a[2];
});
// two spawned thread will be joined at the moment when the `s` ends.
println!("hello from the main thread");
});