How can you implement a thread pool in Python?
a) By using the concurrent.futures.ThreadPoolExecutor class
b) By creating and managing multiple threads manually
c) By using the multiprocessing.Pool class
d) By using the threading.ThreadGroup class
Answer:
a) By using the concurrent.futures.ThreadPoolExecutor class
Explanation:
A thread pool in Python can be implemented using the concurrent.futures.ThreadPoolExecutor
class, which simplifies the process of creating and managing a pool of threads to execute tasks concurrently. This approach is more efficient than manually creating and managing threads, especially when dealing with a large number of tasks.
from concurrent.futures import ThreadPoolExecutor
def task(n):
return f"Task {n} completed"
# Create a thread pool with 5 threads
with ThreadPoolExecutor(max_workers=5) as executor:
results = executor.map(task, range(10))
for result in results:
print(result)
In this example, a thread pool with 5 threads is created using ThreadPoolExecutor
. The map()
method is used to execute the task
function concurrently across multiple threads.
Thread pools are useful for managing a large number of short-lived tasks efficiently, reducing the overhead associated with creating and destroying threads frequently.