qubit_thread_pool/dynamic/thread_pool.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10use std::{
11 sync::Arc,
12 time::Duration,
13};
14
15use qubit_function::{
16 Callable,
17 Runnable,
18};
19
20use qubit_executor::task::spi::TaskEndpointPair;
21use qubit_executor::{
22 TaskHandle,
23 TrackedTask,
24};
25
26use super::thread_pool_builder::ThreadPoolBuilder;
27use super::thread_pool_inner::ThreadPoolInner;
28use crate::{
29 ExecutorServiceBuilderError,
30 PoolJob,
31 ThreadPoolStats,
32};
33use qubit_executor::service::{
34 ExecutorService,
35 ExecutorServiceLifecycle,
36 StopReport,
37 SubmissionError,
38};
39
40/// OS thread pool implementing [`ExecutorService`].
41///
42/// `ThreadPool` accepts fallible tasks, stores accepted waiting tasks in
43/// internal queues, and executes them on worker threads. The global waiting
44/// queue is FIFO, but task start and completion order are not a strict FIFO API
45/// guarantee. Workers are created lazily up to the configured core size, tasks
46/// are queued after that, and the pool may grow up to the maximum size when a
47/// bounded queue is full. Callable submissions return [`TaskHandle`], while
48/// tracked submissions return [`TrackedTask`].
49///
50/// `shutdown` is graceful: already accepted queued tasks are allowed to run.
51/// `stop` is abrupt: queued tasks that have not started are completed
52/// with [`TaskExecutionError::Cancelled`](qubit_executor::TaskExecutionError::Cancelled).
53///
54pub struct ThreadPool {
55 /// Shared pool state and worker coordination primitives.
56 inner: Arc<ThreadPoolInner>,
57}
58
59impl ThreadPool {
60 pub(super) fn from_inner(inner: Arc<ThreadPoolInner>) -> Self {
61 Self { inner }
62 }
63
64 /// Creates a thread pool with equal core and maximum pool sizes.
65 ///
66 /// # Parameters
67 ///
68 /// * `pool_size` - Value applied as both core and maximum pool size.
69 ///
70 /// # Returns
71 ///
72 /// `Ok(ThreadPool)` if all workers are spawned successfully.
73 ///
74 /// # Errors
75 ///
76 /// Returns [`ExecutorServiceBuilderError`] if the resulting maximum pool size is
77 /// zero or a worker thread cannot be spawned.
78 #[inline]
79 pub fn new(pool_size: usize) -> Result<Self, ExecutorServiceBuilderError> {
80 Self::builder().pool_size(pool_size).build()
81 }
82
83 /// Creates a builder for configuring a thread pool.
84 ///
85 /// # Returns
86 ///
87 /// A builder with default core and maximum pool sizes and an unbounded queue.
88 #[inline]
89 pub fn builder() -> ThreadPoolBuilder {
90 ThreadPoolBuilder::default()
91 }
92
93 /// Returns the number of queued tasks waiting for a worker.
94 ///
95 /// # Returns
96 ///
97 /// The number of accepted tasks that have not started yet.
98 #[inline]
99 pub fn queued_count(&self) -> usize {
100 self.inner.queued_count()
101 }
102
103 /// Returns the number of tasks currently held by workers.
104 ///
105 /// # Returns
106 ///
107 /// The number of tasks that workers have taken from the queue and have not
108 /// yet finished processing.
109 #[inline]
110 pub fn running_count(&self) -> usize {
111 self.inner.running_count()
112 }
113
114 /// Returns how many worker threads are still running in this pool.
115 ///
116 /// # Returns
117 ///
118 /// The number of live worker loops still owned by this pool. This is a
119 /// runtime count and is not required to match configured
120 /// [`Self::core_pool_size`] or [`Self::maximum_pool_size`].
121 #[inline]
122 pub fn live_worker_count(&self) -> usize {
123 self.inner.read_state(|state| state.live_workers)
124 }
125
126 /// Returns the configured core pool size.
127 ///
128 /// # Returns
129 ///
130 /// The number of workers kept for normal load before tasks are queued.
131 #[inline]
132 pub fn core_pool_size(&self) -> usize {
133 self.inner.read_state(|state| state.core_pool_size)
134 }
135
136 /// Returns the configured maximum pool size.
137 ///
138 /// # Returns
139 ///
140 /// The maximum number of worker threads this pool may create.
141 #[inline]
142 pub fn maximum_pool_size(&self) -> usize {
143 self.inner.read_state(|state| state.maximum_pool_size)
144 }
145
146 /// Returns a point-in-time snapshot of pool counters.
147 ///
148 /// # Returns
149 ///
150 /// A snapshot containing worker, queue, and task counters observed under
151 /// the pool state lock.
152 #[inline]
153 pub fn stats(&self) -> ThreadPoolStats {
154 self.inner.stats()
155 }
156
157 /// Submits a custom pool job.
158 ///
159 /// This low-level extension point is intended for higher-level services
160 /// that need to pair pool execution with their own task registry or
161 /// cancellation bookkeeping. Prefer the [`ExecutorService`] submission
162 /// methods for ordinary runnable and callable work. Custom job callbacks
163 /// run synchronously on the thread that reaches the corresponding lifecycle
164 /// event and should stay short and non-blocking. Callback panics are
165 /// contained; if an acceptance callback panics, the job is not queued,
166 /// run, or cancelled.
167 ///
168 /// # Parameters
169 ///
170 /// * `job` - Custom job to execute or cancel later.
171 ///
172 /// # Returns
173 ///
174 /// `Ok(())` when the pool accepts the job.
175 ///
176 /// # Errors
177 ///
178 /// Returns [`SubmissionError::Shutdown`] after shutdown, returns
179 /// [`SubmissionError::Saturated`] when the bounded pool cannot accept
180 /// more work, or returns [`SubmissionError::WorkerSpawnFailed`] when a
181 /// required worker cannot be created.
182 #[inline]
183 pub fn submit_job(&self, job: PoolJob) -> Result<(), SubmissionError> {
184 self.inner.submit(job)
185 }
186
187 /// Blocks until all accepted work has completed.
188 ///
189 /// This is a join-style wait for quiescence: it does not request shutdown
190 /// and does not wait for worker threads to exit. Concurrent submissions may
191 /// extend the wait until those accepted jobs also drain.
192 #[inline]
193 pub fn join(&self) {
194 self.inner.wait_until_idle();
195 }
196
197 /// Starts one core worker if the pool has fewer live workers than its
198 /// configured core size.
199 ///
200 /// # Returns
201 ///
202 /// `Ok(true)` if a worker was started, or `Ok(false)` if no core worker
203 /// was needed.
204 ///
205 /// # Errors
206 ///
207 /// Returns [`SubmissionError::Shutdown`] if the pool is shut down, or
208 /// [`SubmissionError::WorkerSpawnFailed`] if worker creation fails.
209 #[inline]
210 pub fn prestart_core_thread(&self) -> Result<bool, SubmissionError> {
211 self.inner.prestart_core_thread()
212 }
213
214 /// Starts all missing core workers.
215 ///
216 /// # Returns
217 ///
218 /// The number of workers started.
219 ///
220 /// # Errors
221 ///
222 /// Returns [`SubmissionError::Shutdown`] if the pool is shut down, or
223 /// [`SubmissionError::WorkerSpawnFailed`] if worker creation fails.
224 #[inline]
225 pub fn prestart_all_core_threads(&self) -> Result<usize, SubmissionError> {
226 self.inner.prestart_all_core_threads()
227 }
228
229 /// Updates the core pool size.
230 ///
231 /// Increasing the core size changes future admission and prestart limits,
232 /// but it does not eagerly create workers or reschedule already queued work.
233 /// Call [`Self::prestart_all_core_threads`] when eager creation is desired.
234 /// Decreasing the core size lets excess idle workers retire according to
235 /// the keep-alive policy.
236 ///
237 /// # Parameters
238 ///
239 /// * `core_pool_size` - New core pool size.
240 ///
241 /// # Returns
242 ///
243 /// `Ok(())` if the size is accepted.
244 ///
245 /// # Errors
246 ///
247 /// Returns [`ExecutorServiceBuilderError::CorePoolSizeExceedsMaximum`] when the
248 /// new core size would exceed the current maximum size.
249 pub fn set_core_pool_size(&self, core_pool_size: usize) -> Result<(), ExecutorServiceBuilderError> {
250 self.inner.set_core_pool_size(core_pool_size)
251 }
252
253 /// Updates the maximum pool size.
254 ///
255 /// Excess workers are not interrupted. They retire after finishing current
256 /// work or timing out while idle.
257 ///
258 /// # Parameters
259 ///
260 /// * `maximum_pool_size` - New maximum pool size.
261 ///
262 /// # Returns
263 ///
264 /// `Ok(())` if the size is accepted.
265 ///
266 /// # Errors
267 ///
268 /// Returns [`ExecutorServiceBuilderError::ZeroMaximumPoolSize`] when the maximum
269 /// size is zero, or [`ExecutorServiceBuilderError::CorePoolSizeExceedsMaximum`]
270 /// when it would be smaller than the current core size.
271 pub fn set_maximum_pool_size(&self, maximum_pool_size: usize) -> Result<(), ExecutorServiceBuilderError> {
272 self.inner.set_maximum_pool_size(maximum_pool_size)
273 }
274
275 /// Updates how long excess idle workers may wait before exiting.
276 ///
277 /// # Parameters
278 ///
279 /// * `keep_alive` - New idle timeout for workers above the core size.
280 ///
281 /// # Returns
282 ///
283 /// `Ok(())` if the timeout is accepted.
284 ///
285 /// # Errors
286 ///
287 /// Returns [`ExecutorServiceBuilderError::ZeroKeepAlive`] when `keep_alive` is
288 /// zero.
289 pub fn set_keep_alive(&self, keep_alive: Duration) -> Result<(), ExecutorServiceBuilderError> {
290 self.inner.set_keep_alive(keep_alive)
291 }
292
293 /// Updates whether core workers may also retire after keep-alive timeout.
294 ///
295 /// # Parameters
296 ///
297 /// * `allow` - Whether core workers are subject to idle timeout.
298 pub fn allow_core_thread_timeout(&self, allow: bool) {
299 self.inner.allow_core_thread_timeout(allow);
300 }
301}
302
303impl Drop for ThreadPool {
304 /// Requests graceful shutdown when the pool value is dropped.
305 fn drop(&mut self) {
306 self.inner.shutdown();
307 }
308}
309
310impl ExecutorService for ThreadPool {
311 type ResultHandle<R, E>
312 = TaskHandle<R, E>
313 where
314 R: Send + 'static,
315 E: Send + 'static;
316
317 type TrackedHandle<R, E>
318 = TrackedTask<R, E>
319 where
320 R: Send + 'static,
321 E: Send + 'static;
322
323 /// Accepts a runnable and queues it for pool workers.
324 fn submit<T, E>(&self, task: T) -> Result<(), SubmissionError>
325 where
326 T: Runnable<E> + Send + 'static,
327 E: Send + 'static,
328 {
329 self.inner.submit(PoolJob::detached(task))
330 }
331
332 /// Accepts a callable and queues it for pool workers.
333 ///
334 /// # Parameters
335 ///
336 /// * `task` - Callable to execute on a pool worker.
337 ///
338 /// # Returns
339 ///
340 /// A [`TaskHandle`] for the accepted task.
341 ///
342 /// # Errors
343 ///
344 /// Returns [`SubmissionError::Shutdown`] after shutdown, returns
345 /// [`SubmissionError::Saturated`] when the bounded pool cannot accept
346 /// more work, or returns [`SubmissionError::WorkerSpawnFailed`] when a
347 /// required worker cannot be created.
348 fn submit_callable<C, R, E>(&self, task: C) -> Result<Self::ResultHandle<R, E>, SubmissionError>
349 where
350 C: Callable<R, E> + Send + 'static,
351 R: Send + 'static,
352 E: Send + 'static,
353 {
354 let (handle, completion) = TaskEndpointPair::new().into_parts();
355 let job = PoolJob::from_task(task, completion);
356 self.inner.submit(job)?;
357 Ok(handle)
358 }
359
360 /// Accepts a callable and queues it with a tracked handle.
361 fn submit_tracked_callable<C, R, E>(&self, task: C) -> Result<Self::TrackedHandle<R, E>, SubmissionError>
362 where
363 C: Callable<R, E> + Send + 'static,
364 R: Send + 'static,
365 E: Send + 'static,
366 {
367 let (handle, completion) = TaskEndpointPair::new().into_tracked_parts();
368 let job = PoolJob::from_task(task, completion);
369 self.inner.submit(job)?;
370 Ok(handle)
371 }
372
373 /// Stops accepting new tasks after already queued work is drained.
374 ///
375 /// Queued and running tasks remain eligible to complete normally.
376 #[inline]
377 fn shutdown(&self) {
378 self.inner.shutdown();
379 }
380
381 /// Stops accepting tasks and cancels queued tasks that have not started.
382 ///
383 /// # Returns
384 ///
385 /// A report containing the number of queued jobs cancelled and the number
386 /// of jobs running at the time of the request.
387 #[inline]
388 fn stop(&self) -> StopReport {
389 self.inner.stop()
390 }
391
392 /// Returns the current lifecycle state.
393 #[inline]
394 fn lifecycle(&self) -> ExecutorServiceLifecycle {
395 self.inner.lifecycle()
396 }
397
398 /// Returns whether shutdown has been requested.
399 #[inline]
400 fn is_not_running(&self) -> bool {
401 self.inner.is_not_running()
402 }
403
404 /// Returns whether shutdown was requested and all workers have exited.
405 #[inline]
406 fn is_terminated(&self) -> bool {
407 self.inner.is_terminated()
408 }
409
410 /// Blocks until the pool has terminated.
411 fn wait_termination(&self) {
412 self.inner.wait_for_termination();
413 }
414}