Thread with 8 posts

jump to expanded post

a 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

Open thread at this post

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()
}
Open thread at this post

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();
Open thread at this post

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

Open thread at this post