pub struct ThreadPool { /* private fields */ }
Expand description
ThreadPool
provides a way to manage and execute tasks concurrently using a fixed number of worker threads.
It allows you to submit tasks that will be executed by one of the available worker threads, providing an efficient way to parallelize work across multiple threads.
Implementations§
Source§impl ThreadPool
impl ThreadPool
Sourcepub fn builder() -> ThreadPoolBuilder
pub fn builder() -> ThreadPoolBuilder
Discovery method for ThreadPoolBuilder
.
Returns a default ThreadPoolBuilder
for constructing a new ThreadPool
.
This method provides a convenient way to start building a ThreadPool
with default settings,
which can then be customized as needed.
§Examples
use base_threadpool::ThreadPool;
let pool = ThreadPool::builder().build();
Sourcepub fn execute<F>(&self, f: F)
pub fn execute<F>(&self, f: F)
Schedules a task to be executed by the thread pool.
Panics if the thread pool has been shut down or if there’s an error sending the job.
§Examples
use base_threadpool::ThreadPool;
use std::sync::{Arc, Mutex};
// Create a thread pool with 4 worker threads
let pool = ThreadPool::builder().num_threads(4).build();
// Create a list of items to process
let items = vec!["apple", "banana", "cherry", "date", "elderberry"];
let processed_items = Arc::new(Mutex::new(Vec::new()));
// Process each item concurrently
for item in items {
let processed_items = Arc::clone(&processed_items);
pool.execute(move || {
// Simulate some processing time
std::thread::sleep(std::time::Duration::from_millis(100));
// Process the item (in this case, convert to uppercase)
let processed = item.to_uppercase();
// Store the processed item
processed_items.lock().unwrap().push(processed);
});
}
Sourcepub fn join(&mut self)
pub fn join(&mut self)
Waits for all worker threads in the pool to finish their current tasks and then shuts down the pool.
This function will block until all workers have completed.
§Examples
use base_threadpool::ThreadPool;
use std::sync::{
atomic::{AtomicU16, Ordering},
Arc,
};
let mut pool = ThreadPool::builder().build();
let counter = Arc::new(AtomicU16::new(0));
(0..100).for_each(|_| {
let counter = Arc::clone(&counter);
pool.execute(move || {
let _ = counter.fetch_add(1, Ordering::SeqCst);
});
});
pool.join();
assert_eq!(counter.load(Ordering::SeqCst), 100);
Sourcepub fn num_threads(&self) -> usize
pub fn num_threads(&self) -> usize
Provides information about the level of concurrency available in the thread pool.
Returns the number of worker threads in the pool.
§Examples
use base_threadpool::ThreadPool;
let pool = ThreadPool::builder().num_threads(4).build();
assert_eq!(pool.num_threads(), 4);