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?