Skip to main content

ThreadPool

Struct ThreadPool 

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

OS thread pool implementing ExecutorService.

ThreadPool accepts fallible tasks, stores accepted waiting tasks in internal queues, and executes them on worker threads. The global waiting queue is FIFO, but task start and completion order are not a strict FIFO API guarantee. Workers are created lazily up to the configured core size, tasks are queued after that, and the pool may grow up to the maximum size when a bounded queue is full. Callable submissions return TaskHandle, while tracked submissions return TrackedTask.

shutdown is graceful: already accepted queued tasks are allowed to run. stop is abrupt: queued tasks that have not started are completed with TaskExecutionError::Cancelled.

Implementations§

Source§

impl ThreadPool

Source

pub fn new(pool_size: usize) -> Result<ThreadPool, ExecutorServiceBuilderError>

Creates a thread pool with equal core and maximum pool sizes.

§Parameters
  • pool_size - Value applied as both core and maximum pool size.
§Returns

Ok(ThreadPool) if all workers are spawned successfully.

§Errors

Returns ExecutorServiceBuilderError if the resulting maximum pool size is zero or a worker thread cannot be spawned.

Source

pub fn builder() -> ThreadPoolBuilder

Creates a builder for configuring a thread pool.

§Returns

A builder with default core and maximum pool sizes and an unbounded queue.

Source

pub fn queued_count(&self) -> usize

Returns the number of queued tasks waiting for a worker.

§Returns

The number of accepted tasks that have not started yet.

Source

pub fn running_count(&self) -> usize

Returns the number of tasks currently held by workers.

§Returns

The number of tasks that workers have taken from the queue and have not yet finished processing.

Source

pub fn live_worker_count(&self) -> usize

Returns how many worker threads are still running in this pool.

§Returns

The number of live worker loops still owned by this pool. This is a runtime count and is not required to match configured Self::core_pool_size or Self::maximum_pool_size.

Source

pub fn core_pool_size(&self) -> usize

Returns the configured core pool size.

§Returns

The number of workers kept for normal load before tasks are queued.

Source

pub fn maximum_pool_size(&self) -> usize

Returns the configured maximum pool size.

§Returns

The maximum number of worker threads this pool may create.

Source

pub fn stats(&self) -> ThreadPoolStats

Returns a point-in-time snapshot of pool counters.

§Returns

A snapshot containing worker, queue, and task counters observed under the pool state lock.

Source

pub fn submit_job(&self, job: PoolJob) -> Result<(), SubmissionError>

Submits a custom pool job.

This low-level extension point is intended for higher-level services that need to pair pool execution with their own task registry or cancellation bookkeeping. Prefer the ExecutorService submission methods for ordinary runnable and callable work. Custom job callbacks run synchronously on the thread that reaches the corresponding lifecycle event and should stay short and non-blocking. Callback panics are contained; if an acceptance callback panics, the job is not queued, run, or cancelled.

§Parameters
  • job - Custom job to execute or cancel later.
§Returns

Ok(()) when the pool accepts the job.

§Errors

Returns SubmissionError::Shutdown after shutdown, returns SubmissionError::Saturated when the bounded pool cannot accept more work, or returns SubmissionError::WorkerSpawnFailed when a required worker cannot be created.

Source

pub fn join(&self)

Blocks until all accepted work has completed.

This is a join-style wait for quiescence: it does not request shutdown and does not wait for worker threads to exit. Concurrent submissions may extend the wait until those accepted jobs also drain.

Source

pub fn prestart_core_thread(&self) -> Result<bool, SubmissionError>

Starts one core worker if the pool has fewer live workers than its configured core size.

§Returns

Ok(true) if a worker was started, or Ok(false) if no core worker was needed.

§Errors

Returns SubmissionError::Shutdown if the pool is shut down, or SubmissionError::WorkerSpawnFailed if worker creation fails.

Source

pub fn prestart_all_core_threads(&self) -> Result<usize, SubmissionError>

Starts all missing core workers.

§Returns

The number of workers started.

§Errors

Returns SubmissionError::Shutdown if the pool is shut down, or SubmissionError::WorkerSpawnFailed if worker creation fails.

Source

pub fn set_core_pool_size( &self, core_pool_size: usize, ) -> Result<(), ExecutorServiceBuilderError>

Updates the core pool size.

Increasing the core size changes future admission and prestart limits, but it does not eagerly create workers or reschedule already queued work. Call Self::prestart_all_core_threads when eager creation is desired. Decreasing the core size lets excess idle workers retire according to the keep-alive policy.

§Parameters
  • core_pool_size - New core pool size.
§Returns

Ok(()) if the size is accepted.

§Errors

Returns ExecutorServiceBuilderError::CorePoolSizeExceedsMaximum when the new core size would exceed the current maximum size.

Source

pub fn set_maximum_pool_size( &self, maximum_pool_size: usize, ) -> Result<(), ExecutorServiceBuilderError>

Updates the maximum pool size.

Excess workers are not interrupted. They retire after finishing current work or timing out while idle.

§Parameters
  • maximum_pool_size - New maximum pool size.
§Returns

Ok(()) if the size is accepted.

§Errors

Returns ExecutorServiceBuilderError::ZeroMaximumPoolSize when the maximum size is zero, or ExecutorServiceBuilderError::CorePoolSizeExceedsMaximum when it would be smaller than the current core size.

Source

pub fn set_keep_alive( &self, keep_alive: Duration, ) -> Result<(), ExecutorServiceBuilderError>

Updates how long excess idle workers may wait before exiting.

§Parameters
  • keep_alive - New idle timeout for workers above the core size.
§Returns

Ok(()) if the timeout is accepted.

§Errors

Returns ExecutorServiceBuilderError::ZeroKeepAlive when keep_alive is zero.

Source

pub fn allow_core_thread_timeout(&self, allow: bool)

Updates whether core workers may also retire after keep-alive timeout.

§Parameters
  • allow - Whether core workers are subject to idle timeout.

Trait Implementations§

Source§

impl Drop for ThreadPool

Source§

fn drop(&mut self)

Requests graceful shutdown when the pool value is dropped.

Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl ExecutorService for ThreadPool

Source§

fn submit<T, E>(&self, task: T) -> Result<(), SubmissionError>
where T: Runnable<E> + Send + 'static, E: Send + 'static,

Accepts a runnable and queues it for pool workers.

Source§

fn submit_callable<C, R, E>( &self, task: C, ) -> Result<<ThreadPool as ExecutorService>::ResultHandle<R, E>, SubmissionError>
where C: Callable<R, E> + Send + 'static, R: Send + 'static, E: Send + 'static,

Accepts a callable and queues it for pool workers.

§Parameters
  • task - Callable to execute on a pool worker.
§Returns

A TaskHandle for the accepted task.

§Errors

Returns SubmissionError::Shutdown after shutdown, returns SubmissionError::Saturated when the bounded pool cannot accept more work, or returns SubmissionError::WorkerSpawnFailed when a required worker cannot be created.

Source§

fn submit_tracked_callable<C, R, E>( &self, task: C, ) -> Result<<ThreadPool as ExecutorService>::TrackedHandle<R, E>, SubmissionError>
where C: Callable<R, E> + Send + 'static, R: Send + 'static, E: Send + 'static,

Accepts a callable and queues it with a tracked handle.

Source§

fn shutdown(&self)

Stops accepting new tasks after already queued work is drained.

Queued and running tasks remain eligible to complete normally.

Source§

fn stop(&self) -> StopReport

Stops accepting tasks and cancels queued tasks that have not started.

§Returns

A report containing the number of queued jobs cancelled and the number of jobs running at the time of the request.

Source§

fn lifecycle(&self) -> ExecutorServiceLifecycle

Returns the current lifecycle state.

Source§

fn is_not_running(&self) -> bool

Returns whether shutdown has been requested.

Source§

fn is_terminated(&self) -> bool

Returns whether shutdown was requested and all workers have exited.

Source§

fn wait_termination(&self)

Blocks until the pool has terminated.

Source§

type ResultHandle<R: Send + 'static, E: Send + 'static> = TaskHandle<R, E>

Result handle returned for an accepted callable task.
Source§

type TrackedHandle<R: Send + 'static, E: Send + 'static> = TrackedTask<R, E>

Tracked handle returned for accepted tasks that expose status.
Source§

fn submit_tracked<T, E>( &self, task: T, ) -> Result<Self::TrackedHandle<(), E>, SubmissionError>
where T: Runnable<E> + Send + 'static, E: Send + 'static,

Submits a runnable task and returns a tracked handle. Read more
Source§

fn is_running(&self) -> bool

Returns whether the service accepts new tasks. Read more
Source§

fn is_shutting_down(&self) -> bool

Returns whether graceful shutdown is in progress. Read more
Source§

fn is_stopping(&self) -> bool

Returns whether abrupt stop is in progress. 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> DropFlavorWrapper<T> for T

Source§

type Flavor = MayDrop

The DropFlavor that wraps T into Self
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

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

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoResult<T> for T

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. 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.