Thread pool
Пул потоков
A group of reusable worker threads that run tasks. It avoids creating a new thread for every task and lets a program limit how many tasks run at once.
Why reuse threads?
Suppose an app needs to generate thumbnails for 100 photos. It could start a thread for each photo, but creating that many threads takes time and memory. With a four-thread pool, each worker processes one photo and then takes another. The app can submit many tasks without giving every task a thread of its own.
What happens when you submit a task?
In a typical pool, submitted work goes into a queue until a worker is available. Once a worker finishes, it can pick up another task. A fixed-size pool caps the number of workers at a configured value; a dynamic pool can add or remove workers within its configured limits. Even with a first-in, first-out queue, tasks can finish in a different order because they take different amounts of time.
The worker limit and queue capacity are separate. Four workers can run at most four tasks at once, but an unbounded queue can hold a growing backlog. If submissions consistently outpace completions, tasks wait longer and consume more memory. A bounded queue limits that backlog, but you still need a policy for when it fills: reject new tasks, for example, or slow the producer down.
Example: overlapping I/O in Python
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
def file_size(path):
return path.stat().st_size
with ThreadPoolExecutor(max_workers=4) as pool:
sizes = list(pool.map(file_size, Path('reports').glob('*.csv')))
Up to four workers can look up file sizes at once. map yields results in input order, not completion order, so a slow early result can delay delivery of later ones. Leaving the with block shuts down the pool and waits for submitted work to finish.
When a pool helps—and when it doesn't
Pools are useful for background jobs and for moving blocking calls off a UI thread or event loop. For CPU-bound code that can run in parallel, start near the number of CPU cores available to the application. In CPython with the GIL enabled, adding threads generally won't speed up pure Python CPU-bound work. For blocking I/O, more workers may help because some spend time waiting, but adding workers won't help if the database connection pool is already the bottleneck.
A pool does not make shared data thread-safe. Also avoid having every worker wait synchronously for a subtask queued in the same pool: no worker will be free to run those subtasks.
How it comes up in interviews
If asked what happens when the pool is full, distinguish busy workers from a full queue. For sizing questions, explain whether the tasks compute or wait, what downstream limits apply, and what you'd measure under load. For example, high queue wait with spare CPU calls for checking I/O and downstream capacity before adding threads.