by yakubin · 4y ago · 0 comments
#![feature(scoped_threads)]
use std::thread;
use std::sync::Mutex;
fn main() {
let a = Mutex::new(0u32);
thread::scope(|s| {
s.spawn(|| {
*a.lock().unwrap() += 1;
});
s.spawn(|| {
*a.lock().unwrap() += 1;
});
});
assert_eq!(*a.lock().unwrap(), 2);
}
A nice glimpse of structured concurrency.[1]: <https://doc.rust-lang.org/std/thread/fn.scope.html>
Edit: removed unnecessary "mut" from declaration of "a".
Scoped threads are such a brilliant thing in the context of lifetimes.
Pre-1.0, we used to have JoinHandle<'a> which let you use the borrow checker to its full potential with multiple threads. This is a big practical hurdle today, where mutices are required even for simple cases which don't suffer data races in practice.
use std::{sync::Mutex, thread, thread::sleep, time::Duration};
fn main() {
static MUTEX: Mutex<String> = Mutex::new(String::new());
let t1 = thread::spawn(|| {
MUTEX.lock().unwrap().push_str("hello ");
});
let t2 = thread::spawn(|| {
sleep(Duration::from_millis(10));
MUTEX.lock().unwrap().push_str("world!");
});
t1.join().unwrap();
t2.join().unwrap();
println!("{}", MUTEX.lock().unwrap());
}
Of course you can't really use it for everything (ie. whatever you put inside `Mutex::new()` needs to be static as well, but still, it's a nice option tooSuper cool not having manual thread joining code.