Skip to content

Commit

Permalink
Add progress reporting example
Browse files Browse the repository at this point in the history
  • Loading branch information
jolisper committed Apr 27, 2024
1 parent 436332a commit 4cc139e
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 1 deletion.
8 changes: 8 additions & 0 deletions 2. Atomics/progress-reporting-parking/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "progress-reporting-parking"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
45 changes: 45 additions & 0 deletions 2. Atomics/progress-reporting-parking/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use std::{
io::{self, Write},
sync::atomic::{AtomicUsize, Ordering::Relaxed},
thread,
time::Duration,
};

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

let main_thread = thread::current();

let items = (0..100).collect::<Vec<_>>();

thread::scope(|s| {
s.spawn(|| {
items.iter().enumerate().for_each(|(i, &item)| {
process_item(item);
num_done.store(i + 1, Relaxed);
main_thread.unpark(); // Wake up the main thread
})
});

loop {
let n = num_done.load(Relaxed);
print_progress(n);
if n == 100 {
break; // All done
}
thread::park_timeout(Duration::from_secs(1));
}
});
}

fn print_progress(percentage: usize) {
match percentage {
p if p >= 100 => println!("\nDone!"),
_ => print!("\rWorking.. {percentage}/100"),
}
io::stdout().flush().unwrap();
}

fn process_item(_item: i32) {
thread::sleep(Duration::from_millis(100));
}
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

resolver = "2"

members = [ "1. Basics of Rust Concurrency/lifetime-mutexguard","1. Basics of Rust Concurrency/scoped-threads", "2. Atomics/stop-flag"]
members = [ "1. Basics of Rust Concurrency/lifetime-mutexguard","1. Basics of Rust Concurrency/scoped-threads", "2. Atomics/progress-reporting-parking", "2. Atomics/stop-flag"]

0 comments on commit 4cc139e

Please sign in to comment.