Hacker News new | ask | show | jobs
by anarki8 475 days ago
I am not sure what are you trying to represent with this example, but here is the exact same thing without any unsafe:

use rayon::prelude::*;

use std::time::{Instant, Duration};

use std::sync::atomic::{AtomicUsize, Ordering};

fn main() {

    let finish_at = Instant::now() + Duration::from_secs(1);

    let number = AtomicUsize::new(0);

    (0..10).into_par_iter().for_each(|_| {
        while finish_at > Instant::now() {
            number.fetch_add(1, Ordering::Relaxed);
        }
    });
}

You can make it even simpler if you would use Mutex instead of atomics. Atomics are more performant though.