m-ou-se / rust-atomics-and-locks

Code examples, data structures, and links from my book, Rust Atomics and Locks.
Other
1.33k stars 120 forks source link

Minor technical mistake in a chapter 2 paragraph Example: Progress Reporting #45

Closed arthurkulchenko closed 1 year ago

arthurkulchenko commented 1 year ago

Type of error

Minor technical mistake

Location of the error

https://marabos.nl/atomics/atomics.html#example-progress-reporting

use std::sync::atomic::AtomicUsize;

fn main() {
    let num_done = AtomicUsize::new(0);

    thread::scope(|s| {
        // A background thread to process all 100 items.
        s.spawn(|| {
            for i in 0..100 {
                process_item(i); // Assuming this takes some time.
                num_done.store(i + 1, Relaxed);
            }
        });

        // The main thread shows status updates, every second.
        loop {
            let n = num_done.load(Relaxed);
            if n == 100 { break; }
            println!("Working.. {n}/100 done");
            thread::sleep(Duration::from_secs(1));
        }
    });

    println!("Done!");
}

Description of the error

Suggestion

use std::sync::atomic::Ordering::Relaxed;
use std::sync::atomic::AtomicUsize;

fn main() {
    static NUM_DONE: AtomicUsize = AtomicUsize::new(0);
    let t = std::thread::spawn(|| {
        for i in 0..100 {
            process(i);
            NUM_DONE.store(i + 1, Relaxed);
        }
    });

    loop {
        let n = NUM_DONE.load(Relaxed);
        if n == 100 { break; };

        println!("working.. {n}/100 done");
        std::thread::sleep(std::time::Duration::from_secs(1));
    }
    t.join().unwrap();
    println!("done!");
}

fn process(_index: usize) {
    std::thread::sleep(std::time::Duration::from_millis(400));
}

Of course it might be platform specific issue: macOs 14.1 Beta (23B5056e) platform arm64 rust: stable 1.72.1

arthurkulchenko commented 1 year ago

My fault, sorry, loop was out of thread scope. Easy to make a mistake when code splitted on different pages