---
name: thread-pool
description: This skill should be used when the user asks about "thread pool pattern", "when to use thread pool", "worker pool", "task queue", "concurrent execution", "manage threads", or mentions needing to manage a pool of workers for parallel task processing.
version: 1.0.0
---

# Thread Pool Pattern

## What Is It
The Thread Pool pattern manages a group of reusable threads (workers) that execute tasks concurrently. Instead of creating a new thread for each task, threads are reused from a pool, improving performance and resource management.

## When to Use
- **Web servers** - Handle multiple concurrent requests
- **Task queues** - Process jobs in parallel with limited workers
- **Image/video processing** - CPU-intensive batch operations
- **Data processing** - Parallel computation with controlled resources
- **Background jobs** - Email sending, report generation
- **Connection pools** - Database connection management

## When NOT to Use
- **Single task** - No need for pool with one operation
- **I/O bound only** - Consider async/await instead
- **Tasks depend on each other** - Complex dependencies cause deadlocks
- **Very long tasks** - Can starve other tasks

## How to Implement

### Implementation Steps
1. Create a fixed number of workers/threads
2. Maintain a task queue for incoming work
3. Workers pull tasks from queue when available
4. Handle task completion and errors
5. Provide graceful shutdown mechanism

### TypeScript Implementation

```typescript
class ThreadPool {
  private workers: Worker[] = [];
  private taskQueue: (() => Promise<unknown>)[] = [];
  private activeWorkers = 0;

  constructor(private size: number) {
    // Initialize workers
  }

  submit<T>(task: () => Promise<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      this.taskQueue.push(async () => {
        try {
          resolve(await task());
        } catch (error) {
          reject(error);
        }
      });
      this.processQueue();
    });
  }

  private processQueue(): void {
    while (this.activeWorkers < this.size && this.taskQueue.length > 0) {
      const task = this.taskQueue.shift()!;
      this.activeWorkers++;
      task().finally(() => {
        this.activeWorkers--;
        this.processQueue();
      });
    }
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/thread-pool.ts` - Basic implementation with task queue
- `examples/thread-pool-advanced.ts` - Real-world example with priority queue

## Related Patterns
- **Object Pool** - Thread Pool is a specialized Object Pool
- **Producer-Consumer** - Tasks are produced, workers consume them
- **Command** - Tasks can be encapsulated as Command objects
