ThreadPool

Struct ThreadPool 

Source
pub struct ThreadPool { /* private fields */ }
Expand description

A thread pool that manages threads and executes jobs in them.

Implementations§

Source§

impl ThreadPool

Source

pub fn new(size: Option<usize>) -> Result<Self, Error>

Create a new thread pool with the given size.

§Arguments
  • size - The number of threads to create in the thread pool. Use None to determine the number of threads automatically.
§Returns

A Result containing the ThreadPool if the creation was successful, or an io::Error if it was unsuccessful.

§Examples
use tinypool::ThreadPool;

// Create a thread pool with 4 threads
let threadpool = ThreadPool::new(Some(4)).unwrap();
// Create a thread pool with the number of threads determined automatically
let threadpool2 = ThreadPool::new(None).unwrap();
Source

pub fn add_to_queue<F>(&self, job: F)
where F: FnOnce() + Send + 'static,

Add a job to the queue. Jobs are executed in the order they are added. If there are no available threads, the job will be queued until a thread is available.

§Arguments
  • job - The job (closure) to execute in a thread pool.
§Examples
use tinypool::ThreadPool;
use std::sync::{Arc, Mutex};

let mut threadpool = ThreadPool::new(Some(4)).unwrap();
let counter = Arc::new(Mutex::new(0));

for _ in 0..100 {
    let counter_thrd = Arc::clone(&counter);
    threadpool.add_to_queue(move || {
        let mut counter = counter_thrd.lock().unwrap();
        *counter += 1;
    });
}

threadpool.join();
assert_eq!(*counter.lock().unwrap(), 100);
Source

pub fn queued_jobs(&self) -> usize

Get the number of queued (and running) jobs.

§Returns
  • usize - The number of queued jobs.
§Examples
use tinypool::ThreadPool;

let mut threadpool = ThreadPool::new(Some(0)).unwrap();

for i in 0..8 {
    threadpool.add_to_queue(move || { println!("{i}"); });
}
assert_eq!(threadpool.queued_jobs(), 8);  // 8 jobs queued

threadpool.set_size(Some(4)).unwrap();
threadpool.join();
assert_eq!(threadpool.queued_jobs(), 0);  // 0 jobs
Source

pub fn size(&self) -> usize

Get the number of threads in the thread pool.

§Returns
  • usize - The number of threads in the thread pool.
§Examples
use tinypool::ThreadPool;

let threadpool = ThreadPool::new(Some(4)).unwrap();
assert_eq!(threadpool.size(), 4);

let threadpool2 = ThreadPool::new(Some(0)).unwrap();
assert_eq!(threadpool2.size(), 0);
Source

pub fn set_size(&mut self, size: Option<usize>) -> Result<(), Error>

Set the number of threads in the thread pool. If increasing the number of threads, this method will not block the main thread. If reducing the number of threads, this method will put closing messages in the queue for the worker threads to receive. So, this method will block the main thread until all those closing messages are received. That means that all jobs before the closing messages need to be processed. Note that some jobs may still be executing in the remaining worker threads, so the queued_jobs() method may return a non-zero value.

§Arguments
  • size - The number of threads to set the thread pool size to. Use None to determine the number of threads automatically.
§Returns

A Result containing () if successful, or an io::Error if unsuccessful.

§Examples
use tinypool::ThreadPool;

let mut threadpool = ThreadPool::new(Some(0)).unwrap();
assert_eq!(threadpool.size(), 0);

for i in 0..8 {
   threadpool.add_to_queue(move || { println!("{i}"); });
}
assert_eq!(threadpool.queued_jobs(), 8);

// increasing thread pool size doesn't block the main thread
threadpool.set_size(Some(8)).unwrap();
assert_eq!(threadpool.size(), 8);
// jobs are now being executed

// decreasing thread pool size blocks the main thread while waiting for all queued jobs to finish
threadpool.set_size(Some(2)).unwrap();
assert_eq!(threadpool.size(), 2);
// threadpool.queued_jobs() may return a non-zero value here (the value is guaranteed to be <= threadpool.size())
assert!(threadpool.queued_jobs() <= threadpool.size());
Source

pub fn join(&mut self)

Wait for all queued jobs to finish and close all threads. This method will block until all queued jobs have finished. It will then close all threads in the thread pool. If you want to wait for all queued jobs to finish, but want to keep the threads running, use ThreadPool::wait() instead.

§Examples
use tinypool::ThreadPool;

let mut threadpool = ThreadPool::new(Some(4)).unwrap();
assert_eq!(threadpool.size(), 4);
assert_eq!(threadpool.queued_jobs(), 0);

for i in 0..8 {
   threadpool.add_to_queue(move || { println!("{i}"); });
}

threadpool.join();
assert_eq!(threadpool.size(), 0);
assert_eq!(threadpool.queued_jobs(), 0);
Source

pub fn wait(&self)

Wait for all queued jobs to finish. This method will block until all queued jobs have finished. If you want to wait for all queued jobs to finish and close all threads, use ThreadPool::join() instead.

§Examples
use tinypool::ThreadPool;

let mut threadpool = ThreadPool::new(Some(4)).unwrap();
assert_eq!(threadpool.size(), 4);
assert_eq!(threadpool.queued_jobs(), 0);

for i in 0..8 {
  threadpool.add_to_queue(move || { println!("{i}") });
}

threadpool.wait();
assert_eq!(threadpool.size(), 4);
assert_eq!(threadpool.queued_jobs(), 0);

Trait Implementations§

Source§

impl Drop for ThreadPool

Source§

fn drop(&mut self)

Drop the thread pool. This will wait for all queued jobs to finish and close all threads. Equivalent to ThreadPool::join().

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.