Cause of the delay?

Here is the code taken from the Mara Bos's book:

use std::{sync::atomic::AtomicUsize, thread, time::Duration};
fn main()
{
    let num_done = AtomicUsize::new(0);
    thread::scope(|s|
    {
        s.spawn(||
        {
            for i in 0..100
            {
                process_item(i); //assuming this takes some time.
                num_done.store(i+1, std::sync::atomic::Ordering::Relaxed);
            }
        });

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

She mentioned that

Once the last item is processed, it might take up to one whole second for the main thread to know, introducing an unnecessary delay at the end.

Why might it take up to one whole second for the main thread to know after the last item is processed?

Because if num_done reaches 100 right when you start sleeping, then it will still continue sleeping for the full duration before checking num_done again.

3 Likes

Sidenote: I'm also reading this book and this exemple amused me because it'll never show "100/100"

1 Like

Assuming the book doesn't answer how to remove the delay. (Not read it but quote reads as if it doesn't.)

The example in park_timeout goes most of the way; you just have to add a few more lines.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.