# HG changeset patch # User Shinji KONO # Date 1610952783 -32400 # Node ID 34aba7ec9efc089e6334dc5eae208c4add0ba178 # Parent 7eb649571bc6c8dc71f2e1ddbeba62443f2d0501 add thread pool diff -r 7eb649571bc6 -r 34aba7ec9efc Cargo.toml --- 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" ] diff -r 7eb649571bc6 -r 34aba7ec9efc src/thread_pool_test/Cargo.toml --- /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 "] +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 diff -r 7eb649571bc6 -r 34aba7ec9efc src/thread_pool_test/src/main.rs --- /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