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:
- Core worker: The worker thread never be terminated except the associated thread pool is closed and the channel is empty.
- 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
impl ThreadPool
Sourcepub fn execute<F>(&self, task_fn: F) -> Result<(), TPError>
pub fn execute<F>(&self, task_fn: F) -> Result<(), TPError>
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
-
Abort: The task was handled by theRejectedTaskHandler::Abort. -
Closed: The channel was closed.
Sourcepub fn active_count(&self) -> usize
pub fn active_count(&self) -> usize
Counts all active worker threads and returns it.
Sourcepub fn shutdown(&self)
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());Sourcepub fn wait(&self) -> Result<()>
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
impl Clone for ThreadPool
Source§fn clone(&self) -> ThreadPool
fn clone(&self) -> ThreadPool
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more