ThreadPool

Struct ThreadPool 

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

A ThreadPool consists of a collection of reusable threads and a bounded channel that is used to transfer and hold submitted tasks.

§Bounded Channel(Queue)

A bounded channel is a concurrent structure that can help to transfer messages across multiple threads. It holds a finite number of elements, which is useful to prevent resource exhaustion.

A bounded channel consists of two sides: Sender and Receiver.

§Sender Side

A sender is used to send a message into a channel. In thread pool, we use the sender to transfer submitted tasks to avalible worker threads.

§Receiver Side

A receiver is used to fetch messages from the channel. There are limited worker threads in a thread pool, for each of which it contains a receiver that is used to fetch tasks from the channel.

§Worker Thread

We use a special structure, Worker, to represent a thread that is always receiving tasks and executing them. In this library, there are two kinds of the worker:

  1. Core worker: The worker thread never be terminated except the associated thread pool is closed and the channel is empty.
  2. Non-core worker: A thread in this worker can be idle if no task is received for a certain period of time(keep_alive_time).

This thread pool will store core workers and non-core workers in two vectors. When you execute a task, it creates a core worker to process the task if the core worker vector is not full, otherwise the task will be sent to the task channel. If the channel buffer is full, it attempts to find an idle worker thread or creates a new non-core worker thread to process the task.

Worker threads will keep fetching tasks from the channel and executing them until the queue is empty and the sender is dropped or no tasks were received for a long time (only non-core thread).

§Rejected Task

New tasks will be rejected when the channel is full and the number of worker threads in the thread pool reaches a certain number(max_pool_size). A rejected task will be handled by the RejectedTaskHandler. You can set the handler for rejected tasks when you build a thread pool with ThreadPoolBuilder.

Implementations§

Source§

impl ThreadPool

Source

pub fn execute<F>(&self, task_fn: F) -> Result<(), TPError>
where F: FnOnce() + Send + 'static,

Executes the given task in the future.

If the task queue is full and no worker thread can be allocated to execute the task, the task will be handled by the setted RejectedTaskHandler.

§Errors
  1. Abort: The task was handled by the RejectedTaskHandler::Abort.

  2. Closed: The channel was closed.

Source

pub fn active_count(&self) -> usize

Counts all active worker threads and returns it.

Source

pub fn shutdown(&self)

Closes a thread pool.

A closed thread pool will not accept any tasks, but will still process tasks in the channel(queue).

§Examples
use jtp::ThreadPoolBuilder;
let thread_pool = ThreadPoolBuilder::default()
    .build();

thread_pool.shutdown();

assert!(thread_pool.execute(|| {
    println!("Hello");
}).is_err());
Source

pub fn is_closed(&self) -> bool

Returns true if the thread pool is closed.

Source

pub fn wait(&self) -> Result<()>

Waits for all worker threads to finish. Note that is worker threads instead of tasks.

If this is called in a worker thread, then the worker thread will not be joined.

Note that this function will close the thread pool because if the thread pool is not closed, worker threads are never be terminated.

§Errors

An error is returned if a thread panics.

§Examples
use jtp::ThreadPoolBuilder;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

let mut thread_pool = ThreadPoolBuilder::default()
    .build();

let sum = Arc::new(AtomicUsize::new(0));
for _ in 0..10 {
    let sum = sum.clone();
    thread_pool.execute(move || {
        // Increase `sum`.
        sum.fetch_add(1, Ordering::SeqCst);
    });
}

// Block current thread until all worker threads are finished.
thread_pool.wait().unwrap();
assert_eq!(10, sum.load(Ordering::Relaxed));

Trait Implementations§

Source§

impl Clone for ThreadPool

Source§

fn clone(&self) -> ThreadPool

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.