| 1 |
use std::thread; |
| 2 |
use std::time::Duration; |
| 3 |
|
| 4 |
use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; |
| 5 |
|
| 6 |
use rand::RngExt; |
| 7 |
|
| 8 |
fn main() { |
| 9 |
let m = MultiProgress::new(); |
| 10 |
let sty = ProgressStyle::with_template( |
| 11 |
"[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}", |
| 12 |
) |
| 13 |
.unwrap() |
| 14 |
.progress_chars("##-"); |
| 15 |
|
| 16 |
let n = 200; |
| 17 |
let pb = m.add(ProgressBar::new(n)); |
| 18 |
pb.set_style(sty.clone()); |
| 19 |
pb.set_message("todo"); |
| 20 |
let pb2 = m.add(ProgressBar::new(n)); |
| 21 |
pb2.set_style(sty.clone()); |
| 22 |
pb2.set_message("finished"); |
| 23 |
|
| 24 |
let pb3 = m.insert_after(&pb2, ProgressBar::new(1024)); |
| 25 |
pb3.set_style(sty); |
| 26 |
|
| 27 |
m.println("starting!").unwrap(); |
| 28 |
|
| 29 |
let mut threads = vec![]; |
| 30 |
|
| 31 |
let m_clone = m.clone(); |
| 32 |
let h3 = thread::spawn(move || { |
| 33 |
for i in 0..1024 { |
| 34 |
thread::sleep(Duration::from_millis(2)); |
| 35 |
pb3.set_message(format!("item #{}", i + 1)); |
| 36 |
pb3.inc(1); |
| 37 |
} |
| 38 |
m_clone.println("pb3 is done!").unwrap(); |
| 39 |
pb3.finish_with_message("done"); |
| 40 |
}); |
| 41 |
|
| 42 |
for i in 0..n { |
| 43 |
thread::sleep(Duration::from_millis(15)); |
| 44 |
if i == n / 3 { |
| 45 |
thread::sleep(Duration::from_secs(2)); |
| 46 |
} |
| 47 |
pb.inc(1); |
| 48 |
let pb2 = pb2.clone(); |
| 49 |
threads.push(thread::spawn(move || { |
| 50 |
thread::sleep(rand::rng().random_range(Duration::from_secs(1)..Duration::from_secs(5))); |
| 51 |
pb2.inc(1); |
| 52 |
})); |
| 53 |
} |
| 54 |
pb.finish_with_message("all jobs started"); |
| 55 |
|
| 56 |
for thread in threads { |
| 57 |
let _ = thread.join(); |
| 58 |
} |
| 59 |
let _ = h3.join(); |
| 60 |
pb2.finish_with_message("all jobs done"); |
| 61 |
m.clear().unwrap(); |
| 62 |
} |