concurrency_limit/
concurrency_limit.rs1use std::process::Command;
2
3use spawn_wait::{ProcessSet, SignalHandler, WaitAnyResult};
4
5fn make_cmd(secs: i32) -> Command {
6 let mut cmd = Command::new("sh");
7 cmd.arg("-c");
8 cmd.arg(format!(
9 "echo Sleeping for {secs} seconds; sleep {secs}",
10 secs = secs
11 ));
12 cmd
13}
14
15fn main() {
16 let mut procs = ProcessSet::with_concurrency_limit(3);
17 for i in 0..5 {
18 procs.add_command((1, i), make_cmd(1));
19 }
20 for i in 0..5 {
21 procs.add_command((2, i), make_cmd(2));
22 }
23 for i in 0..5 {
24 procs.add_command((3, i), make_cmd(3));
25 }
26
27 let mut sh = SignalHandler::default();
28 loop {
29 match procs.wait_any(&mut sh) {
30 WaitAnyResult::NoProcessesRunning => {
31 println!("All done");
32 return;
33 }
34 WaitAnyResult::ReceivedTerminationSignal(_) => {
35 println!("Terminating");
36 procs.sigint_all_and_wait(&mut sh).unwrap();
37 return;
38 }
39 WaitAnyResult::Subprocess(id, r) => {
40 println!("Process \"sleep {} # {}\" finished: {:?}", id.1, id.0, r);
41 }
42 }
43 }
44}