Thread with 5 posts
jump to expanded posta friend asked me about concurrency in Rust and honest to god, I had never done it before, I only just now looked at the Rust manual, and I managed to write something perfectly correct and safe and really simple, first try
Rust really is the future of systems programming huh. fearless, incredibly easy concurrencyβ¦
like, this is a thread-safe one-time-set global flag:
use std::sync::OnceLock;
static VERBOSE: OnceLock<bool> = OnceLock::new();
fn set_verbose_once(value: bool) {
VERBOSE.set(value).unwrap()
}
fn get_verbose() -> bool {
VERBOSE.get().copied().unwrap()
}
and this is a (ridiculous example of) parallelism:
let mut threads = Vec::new();
for i in 0..8 {
threads.push(std::thread::spawn(move || (i as f32).powf(i as f32)));
}
let mut result: f32 = threads
.into_iter()
.map(|thread| thread.join().unwrap())
.sum();
it's amazing having a language where threads are not only this easy to use, but which is safe while doing it, and doesn't overly restrict what you can do. you don't have to read a hundred awful man pages and you don't need to dedicate half your brain to concurrency hazards