Design a Concurrent Fixed-Size Thread Pool with Task Futures
Data Structure DesignModel answerLast updated
Design and implement a fixed-size thread pool with safe task queueing, future result retrieval, exception handling, and graceful or forced shutdown mechanism using basic locks and condition variables.
Design and implement a reusable, fixed-size thread pool from scratch. The system should allow client threads to submit asynchronous tasks, receive handle objects (Futures) to obtain task results or exceptions, and gracefully or forcefully terminate the pool.
You must rely on native synchronization primitives (such as mutexes/locks and condition variables/events). Do not use high-level language built-in thread pool implementations or executor frameworks (e.g., Python's concurrent.futures, Java's ExecutorService, or C++ std::async).
Requirements and API Design
-
Task Submission & Futures:
- Expose a
submit(task)method accepting a callable. - Return a
Futureobject that caller threads can use to block and wait for the result (get()) or retrieve any exception thrown during task execution.
- Expose a
-
Concurrency & Thread Safety:
- Multiple threads may submit work concurrently, including worker threads within the pool submitting sub-tasks.
- Idle worker threads must sleep efficiently on a condition variable without busy-waiting or missing wake-up signals.
- A worker thread must never hold the shared queue lock while executing a user task.
-
Shutdown Modes:
shutdown(graceful=True): Stop accepting new task submissions. Allow already queued and active tasks to finish before stopping all worker threads.shutdown(graceful=False): Stop accepting new submissions, discard pending (unstarted) tasks in the queue, and notify any threads waiting on those unstarted tasks with a cancellation exception.
-
Queue Capacity & Rejection Strategy:
- Support a maximum queue capacity (
max_queue_size). - If the queue is full or if the pool is already shut down, new calls to
submitshould raise aRejectedExecutionError.
- Support a maximum queue capacity (
Constraints & Edge Cases
- Ensure no caller thread remains indefinitely blocked on a
Future.get()call if the pool shuts down or if a task fails/cancels. - Account for potential deadlocks when tasks submitted to the pool wait on other tasks submitted to the same pool.
Hints
Hint 1
Ensure task state transition (Pending -> Completed/Failed/Cancelled) is guarded by a mutex per Future or a unified synchronization mechanism to prevent race conditions during `Future.get()`.
Hint 2
Always invoke user functions *outside* of the primary queue lock. Holding the main queue lock during execution prevents other workers from picking up queued tasks.
Hint 3
When performing a non-graceful shutdown, ensure all waiting futures in the pending queue receive an explicit cancellation signal so calling threads do not block indefinitely.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture & Component Responsibilities
A robust thread pool consists of four primary components:
Future: Acts as a synchronization bridge between the producer (submitter thread) and the consumer (worker thread). It stores the state of execution (PENDING,RUNNING,SUCCESS,FAILURE,CANCELLED), the return value or exception object, and a condition variable to block callers awaiting completion.TaskWrapper: Enapsulates the user-provided function alongside its associatedFutureobject.BoundedQueue: Thread-safe FIFO storage for pending tasks protected by a lock and condition variables (to handle full/empty states).ThreadPool: Manages worker thread lifecycles, accepts submissions, enforces rejection policies, and coordinates graceful/forced shutdowns.
+------------------+ submit(fn) +--------------------+
| Caller Thread | --------------------> | ThreadPool |
+------------------+ +--------------------+
| |
Returns Future Pushes Task
| v
v +--------------------+
+------------------+ | Bounded Queue |
| Future.get() | (Blocks until done) +--------------------+
+------------------+ |
^ Pulls Task
| v
| Completes/Fails Task +--------------------+
+-------------------------------- | Worker Threads |
+--------------------+
Object Model & Thread-Safety Design
State Transitions for Tasks
PENDING$\rightarrow$RUNNING$\rightarrow$SUCCESS/FAILUREPENDING$\rightarrow$CANCELLED(occurs during non-graceful shutdown)
Synchronization Guarantees
- Queue Lock (
queue_mutex): Guards insertion, removal, and queue size updates. Used with condition variablesnot_empty(workers wait for tasks) andnot_full(submitters wait if queue capacity is reached). - Future Lock (
future_mutex): Guards the state of an individual task execution and signals callers waiting onFuture.get(). Decoupling task-specific locks from the main queue lock reduces lock contention.
Object-Oriented Implementation (Python Threading Primitives)
import threading
from collections import deque
from enum import Enum, auto
import typing
class FutureState(Enum):
PENDING = auto()
RUNNING = auto()
SUCCESS = auto()
FAILURE = auto()
CANCELLED = auto()
class RejectedExecutionError(Exception):
"""Raised when a task cannot be accepted by the thread pool."""
pass
class TaskCancelledError(Exception):
"""Raised when awaiting a result from a cancelled task."""
pass
class Future:
def __init__(self):
self._state = FutureState.PENDING
self._result = None
self._exception = None
self._lock = threading.Lock()
self._done_cond = threading.Condition(self._lock)
def get(self, timeout: float = None) -> typing.Any:
with self._lock:
if not self._is_done_state():
signaled = self._done_cond.wait(timeout=timeout)
if not signaled and not self._is_done_state():
raise TimeoutError("Timed out waiting for future result.")
if self._state == FutureState.SUCCESS:
return self._result
elif self._state == FutureState.FAILURE:
raise self._exception
elif self._state == FutureState.CANCELLED:
raise TaskCancelledError("Task was cancelled prior to execution.")
def _is_done_state(self) -> bool:
return self._state in (FutureState.SUCCESS, FutureState.FAILURE, FutureState.CANCELLED)
def set_result(self, result: typing.Any):
with self._lock:
if self._state == FutureState.CANCELLED:
return
self._result = result
self._state = FutureState.SUCCESS
self._done_cond.notify_all()
def set_exception(self, exc: Exception):
with self._lock:
if self._state == FutureState.CANCELLED:
return
self._exception = exc
self._state = FutureState.FAILURE
self._done_cond.notify_all()
def cancel(self):
with self._lock:
if self._state == FutureState.PENDING:
self._state = FutureState.CANCELLED
self._done_cond.notify_all()
class TaskWrapper:
def __init__(self, fn: callable, future: Future):
self.fn = fn
self.future = future
def run(self):
with self.future._lock:
if self.future._state == FutureState.CANCELLED:
return
self.future._state = FutureState.RUNNING
try:
res = self.fn()
self.future.set_result(res)
except Exception as e:
self.future.set_exception(e)
class ThreadPool:
def __init__(self, num_workers: int, max_queue_size: int = 100):
self._num_workers = num_workers
self._max_queue_size = max_queue_size
self._queue = deque()
self._lock = threading.Lock()
self._not_empty = threading.Condition(self._lock)
self._not_full = threading.Condition(self._lock)
self._is_shutdown = False
self._workers = []
for i in range(num_workers):
t = threading.Thread(target=self._worker_loop, name=f"Worker-{i}")
t.daemon = True
t.start()
self._workers.append(t)
def submit(self, fn: callable) -> Future:
future = Future()
task = TaskWrapper(fn, future)
with self._lock:
if self._is_shutdown:
raise RejectedExecutionError("Cannot submit tasks to a shut down pool.")
while len(self._queue) >= self._max_queue_size:
# Wait for queue space or shutdown
self._not_full.wait()
if self._is_shutdown:
raise RejectedExecutionError("Pool shut down while waiting for queue space.")
self._queue.append(task)
self._not_empty.notify()
return future
def _worker_loop(self):
while True:
task = None
with self._lock:
while len(self._queue) == 0 and not self._is_shutdown:
self._not_empty.wait()
if self._is_shutdown and len(self._queue) == 0:
# Termination condition: shutdown and no tasks remain
return
task = self._queue.popleft()
self._not_full.notify()
# Execute the task OUTSIDE the lock
if task:
task.run()
def shutdown(self, graceful: bool = True):
with self._lock:
if self._is_shutdown:
return
self._is_shutdown = True
if not graceful:
# Cancel pending tasks immediately
while len(self._queue) > 0:
task = self._queue.popleft()
task.future.cancel()
# Wake up all worker threads waiting on tasks
self._not_empty.notify_all()
self._not_full.notify_all()
# Join worker threads outside the main lock to prevent deadlock
for worker in self._workers:
worker.join()
Deep Dive: Edge Cases & Concurrency Hazards
1. Lost Wake-Ups & Spurious Wake-ups
To prevent lost wake-ups, condition variables must always be checked inside a state evaluation loop (while condition:). Worker threads check while len(self._queue) == 0 and not self._is_shutdown: self._not_empty.wait().
2. Reclaiming Lock Scope During Execution
Executing task.run() inside with self._lock: would serialize all worker threads, effectively reducing the thread pool to single-threaded execution. Workers extract the task from the queue, immediately release _lock, and execute the user function in isolation.
3. Thread Pool Deadlocks (Task Interdependencies)
If task A is running inside the thread pool and blocks on Future.get() for task B (also submitted to the pool), a potential deadlock occurs if all available workers are occupied with tasks waiting on unstarted dependent tasks.
- Mitigation: Warn callers against submitting recursive/dependent tasks to a fixed-size pool, or implement work-stealing / thread expansion if worker exhaustion occurs.
4. Pool Sizing Guidance
- CPU-Bound Tasks: Optimal worker count $\approx N_{\text{cores}} + 1$. Minimal context switching, keeping execution units saturated.
- I/O-Bound Tasks: Optimal worker count $\approx N_{\text{cores}} \times \left(1 + \frac{\text{Wait Time}}{\text{Compute Time}}\right)$. Higher worker counts compensate for threads blocked on network/disk responses.