Junior — Middle
What is a thread pool and in what cases is its use advisable?
sobes.tech AI
Answer from AI
A thread pool is a set of pre-created threads that are reused to perform tasks. Instead of creating a new thread for each task, a free thread from the pool is taken.
Advantages:
- Reduces overhead of creating and destroying threads.
- Controls the maximum number of threads running simultaneously.
It is advisable to use a thread pool when:
- You need to perform many short tasks in parallel.
- You want to limit the number of threads running at the same time.
Example in Python with ThreadPoolExecutor:
from concurrent.futures import ThreadPoolExecutor
import time
def task(n):
time.sleep(1)
return n * 2
with ThreadPoolExecutor(max_workers=3) as executor:
results = executor.map(task, range(5))
for r in results:
print(r)
Here, a pool of 3 threads is created, which perform 5 tasks.