changeset 11:34aba7ec9efc

add thread pool
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Mon, 18 Jan 2021 15:53:03 +0900
parents 7eb649571bc6
children 70ab6c2f7f6e
files Cargo.toml src/thread_pool_test/Cargo.toml src/thread_pool_test/src/main.rs
diffstat 3 files changed, 64 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/Cargo.toml	Mon Jan 18 13:22:06 2021 +0900
+++ b/Cargo.toml	Mon Jan 18 15:53:03 2021 +0900
@@ -15,4 +15,5 @@
    "src/t01guessing",
    "src/t16thread",
    "src/async_test",
+   "src/thread_pool_test"
 ]
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/thread_pool_test/Cargo.toml	Mon Jan 18 15:53:03 2021 +0900
@@ -0,0 +1,10 @@
+[package]
+name = "thread_pool_test"
+version = "0.1.0"
+authors = ["Shinji KONO <kono@ie.u-ryukyu.ac.jp>"]
+edition = "2018"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+threadpool = "1.0"
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/thread_pool_test/src/main.rs	Mon Jan 18 15:53:03 2021 +0900
@@ -0,0 +1,53 @@
+use threadpool::ThreadPool;
+use std::sync::mpsc::channel;
+
+fn main1() {
+    use std::sync::{Arc, Barrier};
+    use std::sync::atomic::{AtomicUsize, Ordering};
+
+// create at least as many workers as jobs or you will deadlock yourself
+    let n_workers = 42;
+    let n_jobs = 23;
+    let pool = ThreadPool::new(n_workers);
+    let an_atomic = Arc::new(AtomicUsize::new(0));
+
+    assert!(n_jobs <= n_workers, "too many jobs, will deadlock");
+
+// create a barrier that waits for all jobs plus the starter thread
+    let barrier = Arc::new(Barrier::new(n_jobs + 1));
+    for _ in 0..n_jobs {
+        let barrier = barrier.clone();
+        let an_atomic = an_atomic.clone();
+
+        pool.execute(move|| {
+            // do the heavy work
+            an_atomic.fetch_add(1, Ordering::Relaxed);
+
+            // then wait for the other threads
+            barrier.wait();
+        });
+    }
+
+// wait for the threads to finish the work
+    barrier.wait();
+    assert_eq!(an_atomic.load(Ordering::SeqCst), /* n_jobs = */ 23);
+    println!("barrier done");
+}
+fn main() {
+
+    let n_workers = 4;
+    let n_jobs = 8;
+    let pool = ThreadPool::new(n_workers);
+
+    let (tx, rx) = channel();
+    for _ in 0..n_jobs {
+        let tx = tx.clone();
+        pool.execute(move || {
+            tx.send(1).expect("channel will be there waiting for the pool");
+        });
+    }
+
+    assert_eq!(rx.iter().take(n_jobs).fold(0, |a, b| a + b), 8);
+    println!("pool done");
+    main1();
+}
\ No newline at end of file