From c7975c1859593fe06ee0fd193c6c269eecd9d518 Mon Sep 17 00:00:00 2001 From: "Christoph J. Scherr" Date: Mon, 16 Sep 2024 10:23:28 +0200 Subject: [PATCH] threadpool example --- Cargo.lock | 16 ++++++++++++++++ Cargo.toml | 2 +- members/tpdemo/Cargo.toml | 7 +++++++ members/tpdemo/src/main.rs | 25 +++++++++++++++++++++++++ 4 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 members/tpdemo/Cargo.toml create mode 100644 members/tpdemo/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index db4a39b..53ca47d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4661,6 +4661,15 @@ dependencies = [ "once_cell", ] +[[package]] +name = "threadpool" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" +dependencies = [ + "num_cpus", +] + [[package]] name = "time" version = "0.3.36" @@ -4885,6 +4894,13 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" +[[package]] +name = "tpdemo" +version = "0.1.0" +dependencies = [ + "threadpool", +] + [[package]] name = "tracing" version = "0.1.40" diff --git a/Cargo.toml b/Cargo.toml index 2e3fc13..a999fff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,7 +30,7 @@ members = [ "members/arithmetics", "members/egui-demo", "members/rfd-demo", - "members/iter-prod", + "members/iter-prod", "members/tpdemo", ] default-members = [ ".", diff --git a/members/tpdemo/Cargo.toml b/members/tpdemo/Cargo.toml new file mode 100644 index 0000000..cd14a43 --- /dev/null +++ b/members/tpdemo/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "tpdemo" +version = "0.1.0" +edition = "2021" + +[dependencies] +threadpool = "1.8.1" diff --git a/members/tpdemo/src/main.rs b/members/tpdemo/src/main.rs new file mode 100644 index 0000000..7982a3e --- /dev/null +++ b/members/tpdemo/src/main.rs @@ -0,0 +1,25 @@ +use std::sync::{Arc, Mutex}; + +use threadpool::ThreadPool; + +struct Fish(i32); + +fn main() { + let thing: Arc> = Arc::new(Mutex::new(Fish(0))); + + let tp = ThreadPool::new(20); + + while thing.lock().unwrap().0 < 200 { + let thing = thing.clone(); + tp.execute(move || { + do_thing(thing); + }); + } +} + +fn do_thing(thing: Arc>) { + println!("blubb"); + #[allow(deprecated)] + std::thread::sleep_ms(1000); + thing.lock().unwrap().0 += 1; +}