Hacker News new | ask | show | jobs
by GlitchMr 3156 days ago
The issue really is lack of scoped threads forcing usage of reference counting to figure out when to drop a value. With crossbeam scoped threads implementation this looks much nicer.

    extern crate crossbeam;
    
    use std::sync::Mutex;
    
    fn main() {
        let counter = Mutex::new(0);
        crossbeam::scope(|scope| for _ in 0..10 {
            scope.spawn(|| *counter.lock().unwrap() += 1);
        });
        println!("{:?}", counter);
    }
Four lines to declare a mutex, start 10 threads that all lock that mutex, increase value behind mutex, unlock mutex, and join all spawned threads. There is a lot going on here (unwrap is arguably a noise here however, but the rest is straight to the point).

Also, it's possible to use atomic ints here instead of mutex. Verbosity of mutex actually helps a bit, because locking is fairly expensive and it's better to avoid locking if possible.