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
First issue:
Scoping should be changed to thread joining. Otherwise it will keep it untill spawned thread will finish proccess.
Second issue:
If num_done is not static it will be sugessted to be moved to thread (if joining used).
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
Type of error
Minor technical mistake
Location of the error
https://marabos.nl/atomics/atomics.html#example-progress-reporting
Description of the error
Suggestion
Of course it might be platform specific issue: macOs 14.1 Beta (23B5056e) platform arm64 rust: stable 1.72.1